I want to query services between two dates and sum their prices. When I try to use func.sum with Services.query, I get TypeError: BaseQuery object is not callable. How do I query using a function with Flask-SQLAlchemy?
Services.query(func.sum(Services.price)).filter(Services.dateAdd.between(start, end))
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Model.query is a shortcut to db.session.query(Model), it’s not callable. If you’re not querying a model, continue to use db.session.query(...) as you would with regular SQLAlchemy.
db.session.query(db.func.sum(Services.price)).filter(
Services.dateAdd.between(start, end)
)
Method 2
fwiw after this long time, you can use Flask-SQLAlchemy syntax by using:
Services.query(func.sum(Services.price)).filter(Services.dateAdd.between(start, end)).scalar() # or you can use .scalar() ; .one() ; .first() ; .all() depending on what you want to achieve
Basically, syntax Model.query(...).filter(...) needs to end with what you want to get. This is what is missing from your query generating the error.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0