1

The database is near 5 millions rows. I declare a model like below:

class Amodel(db.Model):
     id = db.Column(db.Integer, primary_key=True)
     date = db.Column(db.String)
     money = db.Column(db.String)
  • I made a index of money column and it doesn't affect result.

Way 1 - session.query:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)
s1 = db.session.query(Amodel).filter(Amodel.money=='1000').all()

Way 2 - Model.query:

s2 = Amodel.query.filter(Amodel.money=='1000').all()

Time consumption

test1:
s1:0.06102442741394043
s2:0.6709990501403809

test2:
s1:0.0010263919830322266
s2:0.6235842704772949

test3:
s1:0.0029985904693603516
s2:0.5942485332489014

They got the same result but time consumption is so different. I usually use way2 for query because I think it's more readble. Could someone explain what's happen inside and how to optimize?

Fanco
  • 54
  • 3
  • 1
    I found [this SO answer](https://stackoverflow.com/questions/18600142/sqlalchemy-db-session-query-vs-model-query/41471196#41471196) resourceful. Mentions when to use and which is preferred. It really boils down to the situation. For readability, way2 is much better, but has some limitations as mentioned [here](https://stackoverflow.com/questions/12350807/whats-the-difference-between-model-query-and-session-querymodel-in-sqlalchemy/14553324#14553324) – P0intMaN May 07 '22 at 06:24
  • 1
    Could you show us how you are benchmarking this code? Does the s1 time include the setup or just the evaluation of the query? I have a hunch that it's due to Flask-SQLAlchemy grabbing a new `Session` object during `Model.quey` – tzengia Jun 11 '22 at 07:06
  • I would imagine both queries generate the same SQL. – snakecharmerb Oct 01 '22 at 21:21

0 Answers0