Django queryset ordering by _set



我有这个模型:

class Person(models.Model):
    name = models.CharField()
    likes = models.ManyToManyField(Image)
class Image(models.Model):
    name = ...
    image = ...

如果我使用[x.person_set.count() for x in Image.objects.all()],我得到每个图像有多少人喜欢。

现在我需要排序列表。我想写Image.objects.all().order_by('person_set.count()')

我需要得到一个所有图片的列表,按照人们喜欢它的程度排序。

我该怎么做?

这可以在一次查询中完成您想要的一切(# of likes, order by count)。

from django.db.models import Count
Image.objects.annotate(Count("person")).order_by("person__count")

相关内容

最新更新