相关对象如何订购查询? [英] How to order a queryset by related objects count?
问题描述
我的 models.py
目前设置如下:
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')
无论如何,从这可以理解,2个漫画可以共享相同的话题,但每个漫画只能有一个话题。现在我需要根据与它们相关联的漫画对象的数量排列主题模型的对象列表。例如,我有一个名为Unsorted的主题,与15个漫画相关联,另一个题为Funny with 5漫画的主题。我希望我的查询集的排序方式是Unsorted来自Funny对象。
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!
推荐答案
您可以这样做:
from django.db.models import Count
# ...
Topic.objects.annotate(cc=Count('comic')).order_by('-cc')
这篇关于相关对象如何订购查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!