I’m using flask as a python framework with sqlalchemy. The models use the query_property which helps me build queries:
class Person(object):
query = db_session.query_property()
....
persons = Person.query.all()
Each person has a city, state and country where he lives in and I want to gather all results and output something like:
Country State City Persons(count)
================================================================================
US NY New York 10
DE Berlin Berlin 100
This obviously needs a select count and group by country, state, city. The group by thing works but I dont know how to implement the counting since query property has no select method in which case I would write:
Person.query.select([Person.country, Person.state, Person.city, func.count(Person.id)]).all()
Anyone with an idea how to use query_property with group_by and count?
You are right – you cannot do it using
query_propertybecause it implicitely selects the whole object (all attributes of it), so adding thegroup_bywould not produce the desired result because undesired columns are included in the non-aggregate part of the query.However you can simply use a
db_session.query([Person.country, ...]).group_by(...). So all you need to do is to adddb_sessionproperty to thePersonclass along withqueryand then use it to create a desired query explicitely: