我有这个模型:
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()] 我会知道有多少人喜欢每张图片。
现在我需要订购 list 。我想要像 Image.objects.all().order_by('person_set.count()')
我需要获取所有图像的列表,这些图像按人们喜欢它的程度排序。
我该怎么做?
请您参考如下方法:
这会在一个查询中完成您想要的一切(点赞数和按计数排序)。
from django.db.models import Count
Image.objects.annotate(Count("person")).order_by("person__count")
