How to order a queryset by related objects count?

老子叫甜甜 提交于 2019-12-14 02:44:03

问题


My models.py is currently set up as follows:

class Topic(models.Model):
    topic = models.CharField(max_length = 50)

    def __str__(self):
        return self.topic

class Comic(models.Model):
    ...
    topic = models.ForeignKey(Topic, blank = True, null = True,
    related_name = 'comics')

Anyway, from this its understandable that 2 comics can share the same topic, however, each comic can only have one topic. Now I need a list of objects of the Topic model ordered according to the number of Comic objects associated with them. For example, say I have a Topic called Unsorted which is associated with 15 comics and another Topic called Funny with 5 comics. I want my query set to be ordered in a way that the Unsorted comes before the Funny object.

Topic.objects.all().order_by('-comics')

I tried this but it did not really work, the result wasn't sorted the right way, even though there wasn't an error. So any solutions? Thanks!


回答1:


You can do this:

from django.db.models import Count

# ...    

Topic.objects.annotate(cc=Count('comic')).order_by('-cc')


来源:https://stackoverflow.com/questions/33575574/how-to-order-a-queryset-by-related-objects-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!