'Query difference between db.session.query and Model.query in flask-SQLAlchemy
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|