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!

3 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.

Leave a Reply

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