Вопрос

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_property because it implicitely selects the whole object (all attributes of it), so adding the group_by would 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 add db_session property to the Person class along with query and then use it to create a desired query explicitely:

class Person(object):
    session = db_session
    query = db_session.query_property()
    ....

Другие советы

You can use the add_columns method on Person.query to append computed values:

Person.query.add_columns(func.count(...)).group_by(...).all()

Keep in mind that you get back a list of tuples (not Person objects). However, each tuple contains the Person object and the computed value:

[(<Person object>, 3), (<Person object>, 7), ...]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top