如何计算 Django 中具有精确字段值的所有 ForeignKey 模型?

How to count all ForeignKey models with exact field values in Django?

我不确定这是否可能,但我想计算与具有确切 vote_type 属性的模型关联的所有投票。

这是模型:

class Link(models.Model):
    title       = models.CharField(max_length=200)
    . . . 

class Vote(models.Model):
    UP, DOWN = range(2)
    TYPE_CHOICES = [(UP, "Upvote"), (DOWN, "DownVote")]

    link = models.ForeignKey(Link, related_name='votes')
    vote_type = models.IntegerField(choices=TYPE_CHOICES, db_index=True)
    . . . 

我用这个来统计所有选票:

Link.objects.annotate(ups=Count('votes')).order_by('-ups')

我想也许我可以用它来实现我想要的:

Link.objects.annotate(ups=Count('votes__vote_type__exact=1')).order_by('-ups')

但我似乎不能在这里使用 filter() 语法。

我正在使用 Django 1.8.4。

您可以在执行注释之前根据类型筛选投票。

Link.objects.filter(votes__vote_type=1).annotate(ups=Count('votes')).order_by('-ups')

来源:https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#order-of-annotate-and-filter-clauses