1

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')
Ben
  • 51,770
  • 36
  • 127
  • 149
Victor Neo
  • 3,042
  • 1
  • 17
  • 13

1 Answers1

5

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
zzzeek
  • 72,307
  • 23
  • 193
  • 185