Django: Order a model by a many-to-many field

后端 未结 3 1656
鱼传尺愫
鱼传尺愫 2021-02-07 21:19

I am writing a Django application that has a model for People, and I have hit a snag. I am assigning Role objects to people using a Many-To-Many relationship - where Roles have

3条回答
  •  爱一瞬间的悲伤
    2021-02-07 21:59

    Something like this in SQL:

    select p.*, max (r.Weight) as HeaviestWeight
    from persons p
    inner join RolePersons rp on p.id = rp.PersonID
    innerjoin Roles r on rp.RoleID = r.id
    group by p.*
    order by HeaviestWeight desc
    

    Note: group by p.* may be disallowed by your dialect of SQL. If so, just list all the columns in table p that you intend to use in the select clause.

    Note: if you just group by p.ID, you won't be able to call for the other columns in p in your select clause.

    I don't know how this interacts with Django.

提交回复
热议问题