SQLAlchemy Group By With Full Child Objects

后端 未结 1 959
礼貌的吻别
礼貌的吻别 2020-12-16 21:29

Imagine the following Media table:

| site       | show_id | time |
| ---------------------|-------|
| CNN        | 1       | \'a\'   |
| ABC        | 2               


        
相关标签:
1条回答
  • 2020-12-16 21:56

    In SQL the GROUP BY clause condenses the grouped rows into a single row, based on the grouping expressions. My guess is that you are using SQLite, or an older version of MySQL, since you are allowed to select non-aggregates without them being functionally dependent on the grouping expressions. The results contain values from an unspecified row per group in that case, which is seldom — if ever — useful.

    A solution is to ORDER BY instead of GROUP BY in SQL and then group in Python based on the order expressions:

    from itertools import groupby
    from operator import attrgetter
    
    listings = session.query(Media).\
        filter(Media.site == "CNN").\
        order_by(Media.show_id).\
        all()
    
    # Materialize the subiterators to lists
    listings = [list(g) for k, g in groupby(listings, attrgetter('show_id'))]
    
    0 讨论(0)
提交回复
热议问题