Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order objects according to some attribute of the child in sqlalchemy?

Here is the situation: I have a parent model say BlogPost. It has many Comments. What I want is the list of BlogPosts ordered by the creation date of its' Comments. I.e. the blog post which has the most newest comment should be on top of the list. Is this possible with SQLAlchemy?

like image 248
Haldun Avatar asked Nov 25 '25 06:11

Haldun


2 Answers

http://www.sqlalchemy.org/docs/05/mappers.html#controlling-ordering

As of version 0.5, the ORM does not generate ordering for any query unless explicitly configured.

The “default” ordering for a collection, which applies to list-based collections, can be configured using the order_by keyword argument on relation():

like image 115
GHZ Avatar answered Nov 26 '25 19:11

GHZ


I had the same question as the parent when using the ORM, and GHZ's link contained the answer on how it's possible. In sqlalchemy, assuming BlogPost.comments is a mapped relation to the Comments table, you can't do:

session.query(BlogPost).order_by(BlogPost.comments.creationDate.desc())

, but you can do:

session.query(BlogPost).join(Comments).order_by(Comments.creationDate.desc())


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!