我有一个游戏模型和一个订阅模型:
class Game(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
cover = models.ImageField(upload_to='cover_images')
def __str__(self):
return self.title
class Meta:
ordering = ['title']
class Subscription(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
game = models.ForeignKey(Game, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return str(self.id)
现在,我试图找出如何根据订阅者数量对游戏进行排序。
答案 0 :(得分:3)
您可以在Django> = 2.0中进行此操作:
class Game(models.Model):
# Previous code
class Meta:
ordering = [Count('subscription').desc(nulls_last=True)]
在旧版本中,您可以执行以下操作:
Game.objects.all().annotate(num_subscribers=Count('subscription')
.order_by('-num_subscribers')