Flask Set-up: SQLAlchemy ORM vs. Flask_SQLAlchemy ORM

Below I walk through the difference between Flask app set-up with 1) SQLAlchemy ORM and 2) Flask_SQLAlchemy ORM. While the names can throw you off, they are indeed different. Flask_SQLAlchemy is a layer that sits on top of SQLAlchemy, allowing use of both the SQL and ORM tools. That said, Flask_SQLAlchemy’s set-up involves a bit more “magic,” which can make it confusing. First, the SQLAlchemy ORM Flask app set-up:

Flask_SQLAlchemy’s set-up creates near identical results, but with less code and more “magic”:

Notice in the comments above a couple important details that aren’t easy to find in documentation:

  • Base  in example 1 is equivalent to db.Model  in example 2
  • engine  in example 1 is equivalent to db.engine  in example 2
  • session  in example 1 is equivalent to db.session  in example 2

All in, which you choose doesn’t make much difference for smaller/simpler apps, but consistent set-up will save a lot of headache. For further background reading on what all of the above things actually are/are doing, as well as more info on set-up, I recommend:

Please leave thoughts or questions in the comments below!

7 comments

  1. Thank you very much! Just getting started with flask_sqlalchemy and was a bit confused seeing the different ways things were done in different tutorials.

  2. I didn’t know that both SQLAlchemy and Flask-SQLAlchemy are different Until I visited this site.
    Thanks for clarification.

  3. I’m just looking into flask and sqlalchemy and I seem to be missing something here, I appreciate this is not a full example, but a little help with the below would be appreciated.

    In the above Flask-SQLAlchemy ORM Example you have…

    from app import models
    models.db.create_all()

    Which seems to mean that you have 2 instances of db, is that right and if so is there anything special with how db is setup in models or is it the same as setup __init__.py?

    Thanks

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.