2

Say I have a model in my Flask application like this:

class Foo(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     bar = db.Column(db.String)

In a Flask view, I want to query my database to retrieve a record of this type.

In tutorials I've seen people run such a query in two ways: using the flask.ext.sqlalchemy.SQLAlchemy configuration or the model.

Using flask.ext.sqlalchemy.SQLAlchemy

The app is set up something like this ...

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object(os.environ['MY_SETTINGS'])
db = SQLAlchemy(app)

Then the query in the view looks like this ...

my_query = db.session.query(Foo).filter_by(id=some_id)

Using the model

The other way I've seen the query executed is using the model, like this ...

import Foo
my_query = Foo.query.filter_by(id=some_id)

What's the difference?

As far as I can tell, the query returns exactly the same thing. So it's hard for me to tell which method I should be using. Or does it make no difference?

What about when it comes to creating and deleting records?

mfitzp
  • 15,275
  • 7
  • 50
  • 70
freethebees
  • 957
  • 10
  • 24

1 Answers1

1

It's exactly the same thing, but coming from two different approaches.

The classic SQLAlchemy approach is db.session.query(Foo).filter_by(id=some_id).

Then Flask-SQLAlchemy, among other things, add a property to all models to enable the second approach Foo.query.filter_by(id=some_id).

Additional context (if needed): the second approach mimics the one Django ORM is using, but if you look for SQLAlchemy material on the web you'll mostly find the first approach.

freethebees
  • 957
  • 10
  • 24
b4stien
  • 1,810
  • 13
  • 14
  • Thanks @b4stien. I did wonder whether they might just the same thing and down to preference. It makes sense that they might mimic the Django ORM. It's a shame none of the early-stage tutorials I've seen have mentioned this quirk. – freethebees Mar 24 '16 at 14:46