QuerySet,在多个字段上使用annotate()

时间:2013-05-27 18:34:04

标签: django

这是 models.py

class CompetitionEntry(models.Model):
    submitter = models.ForeignKey(User)
    pic = models.ImageField(upload_to=images, blank=True, null=True)

class CompetitionEntryVote(models.Model):
    voted_entry = models.ForeignKey(CompetitionEntry)

class Entrylikes(models.Model):
    ip_address    = models.IPAddressField()
    liked_entry   = models.ForeignKey(CompetitionEntry)

这是 views.py (我认为问题在这里)

def show_all_entries(request, id):
    entries = CompetitionEntry.objects.filter(competition__id__exact=comp.id).annotate(vote_count=Count('competitionentryvote'), likes_count=Count('entrylikes'))

    return render(request, "show_all.html", {
        "entries": entries,
        })

show_all.html

{% for item in entries %}

Votes = {{item.vote_count}}   Likes= {{item.likes_count}}

{% endfor %}
  1. 这里的问题是投票和喜欢在输出中是相同的。 我,e votes = likes = likes

  2. 如果我重写视图只显示其中一个投票或赞成,那么页面就可以正常运行。

  3. 以及 views.py 如果我使用entries = CompetitionEntry.objects.filter(competition__id__exact=comp.id).annotate(vote_count=Count('competitionentryvote')).annotate(likes_count=Count('entrylikes')),我会得到与上面1相同的结果

1 个答案:

答案 0 :(得分:2)

Count聚合通过映射到SQL COUNT()表达式来工作。请参阅the documentation here

由于您提供的查询只会为整个查询生成一组行,因此COUNT()的值可能与您的情况相同。您可以尝试按照文档中的建议设置distinct=True

  

如果distinct = True,则计数将仅包含唯一实例。这是COUNT(DISTINCT)的等效SQL。默认值为False。

CompetitionEntry.objects.filter(...).annotate(vote_count=Count('competitionentryvote', distinct=True))
   .annotate(likes_count=Count('entrylikes', distinct=True))