0

我不确定这是否可能,但我想计算与具有确切 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。

4

1 回答 1

2

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

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

于 2015-10-15T18:33:51.330 回答