Ravi Kumar
Ravi Kumar

Reputation: 1797

sqlalchemy return query grouped to user_id

Example model:

class Order(Base):
    __tablename__ = 'order'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer)

return list with objects grouped to user_id's

required sample output:

[(5, [<dal.model.order.Orders object at 0x7fc17770f240>, <dal.model.order.Orders object at 0x7fc17770f2b0>]),
(8, [<dal.model.order.Orders object at 0x7fc14470f270>])]
# 5 and 8 are user_id's

Need sqlalchemy query to get output as above.

Upvotes: 0

Views: 356

Answers (1)

Petr Blahos
Petr Blahos

Reputation: 2433

That is not a task for group by. Group by will allow you perform aggregation.

Here you could for example loop through the result and build a dictionary (such as d = collections.defaultdict(list), d[result.user_id].append(result)) which you can later easily covert to a list.

Upvotes: 1

Related Questions