Order by Count of OneToMany Elixir Relationship

1.4k Views Asked by At

I am using Elixir for ORM but I have a problem trying to Order by a Relationship.

What I am trying to do is to get a list of users sorted by the number of posts they have. I have tried ways such as

User.query.join(User.posts).order_by(func.count(User.posts)).all()

without any success.

Here are my Elixir entities:

class User(Entity):
    username = Field(Unicode(100))
    posts = OneToMany('Post', inverse='user')


class Post(Entity):
    content = Field(Unicode(20000))
    user = ManyToOne('User')
1

There are 1 best solutions below

1
On BEST ANSWER

this is a common question and an example query is in the ORM tutorial at: http://www.sqlalchemy.org/docs/orm/tutorial.html#using-subqueries . Just change where it says order_by(User.id) to say order_by(stmt.c.address_count):

>>> from sqlalchemy.sql import func
>>> stmt = session.query(Address.user_id, func.count('*').\
...         label('address_count')).\
...         group_by(Address.user_id).subquery()

>>> for u, count in session.query(User, stmt.c.address_count).\
...     outerjoin(stmt, User.id==stmt.c.user_id).order_by(stmt.c.address_count): 
...     print u, count