I am using sqlalchemy ORM with declarative extensions in a Flask project for a web API. The Flask documentation shows how to execute query properly inside an endpoint here
Now this is all good, but what if i want to execute a group by query. For example given the user domain object in the flask documentation:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True)
email = Column(String(120), unique=True)
I want to retrieve the sum of ids for all the users with the same name (doesn't make sense, take it as toy example for sake of simplicity!). In pure SQL i could do it easily with:
select name, sum(id) from user group by name
However inside an endpoint the reccomanded way to execute a query (again see here ) is to start from a ref to the domain object User, for instance:
User.query.filter(User.name == 'admin').first()
To execute a group-by query I would rather use something like this (which indeed works!):
#see database module http://flask.pocoo.org/docs/0.12/patterns/sqlalchemy/#declarative)
from database import db_session
@app.route('/')
def index():
db_session.query(func.sum(User.id).label('num_id'), User.name).group_by(User.name).all()
In this case the query starts from db_session. Is this correct and safe? Remeamber we are in a concurrent application inside Flask.
Any help?
It's fine. But I usually use . with_entities(*entities) for such cases:
User.query.filter(filters).with_entities(User.name.label('name'), func.count(User.id).label('count')).group_by(User.name)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.