Django ORM表关系

时间:2013-12-12 18:30:59

标签: python django django-models django-orm

我的模型定义如下:

class Games(models.Model):
    title = models.CharField(max_length=50)
    owned = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)


class Votes(models.Model):
    game = models.ForeignKey(Games)
    created = models.DateTimeField(auto_now_add=True)

我在我看来正在做以下事情:

wanted = Games.objects.filter(owned=0)
for game in wanted:
    game.vote = Votes.objects.all().filter(game_id=game.id).count()
wanted = sorted(wanted, key=attrgetter('vote'), reverse=True)

它运行正常,但有更多的Django方式吗?

1 个答案:

答案 0 :(得分:1)

from django.db.models import Count
Games.objects.filter(owned=0).annotate(vote=Count('votes')).order_by('-vote')

有关详细信息,请参阅Django aggregation