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

后端 未结 3 1654
鱼传尺愫
鱼传尺愫 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 22:09

    Django 1.1 (currently beta) adds aggregation support. Your query can be done with something like:

    from django.db.models import Max
    People.objects.annotate(max_weight=Max('roles__weight')).order_by('-max_weight')
    

    This sorts people by their heaviest roles, without returning duplicates.

    The generated query is:

    SELECT people.id, people.name, MAX(role.weight) AS max_weight
    FROM people LEFT OUTER JOIN people_roles ON (people.id = people_roles.people_id)
                LEFT OUTER JOIN role ON (people_roles.role_id = role.id)
    GROUP BY people.id, people.name
    ORDER BY max_weight DESC
    

提交回复
热议问题