Django QuerySet,在多个字段上使用annotate()
这是型号。pyDjango QuerySet,在多个字段上使用annotate(),django,Django,这是型号。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 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(我想问题就在这里)
show_all.html
{% for item in entries %}
Votes = {{item.vote_count}} Likes= {{item.likes_count}}
{% endfor %}
entries=CompetitionEntry.objects.filter(competition\uu-id\uu-exact=comp.id)。注释(vote\u-count=count('competitionentryvote')。注释(likes_-count=count('entrylikes'))
我得到与上面1相同的结果Count
聚合通过映射到SQLCount()
表达式来工作。看
由于您提供的查询只会为整个查询生成一组行,COUNT()
的值在您的情况下可能是相同的。您可以尝试按照文档中的建议设置distinct=True
:
如果distinct=True,则计数将仅包括唯一实例。这是COUNT(DISTINCT)的SQL等价物。默认值为False
即
我已经从上面的models.py和views.py中删除了内容,因为它们太大,无法粘贴到这里。希望这不会带走问题的要点。很抱歉,我没有抓住要点(我只有SQL的基本知识)。那么,这里不可能同时包含这两个计数吗?
{% for item in entries %}
Votes = {{item.vote_count}} Likes= {{item.likes_count}}
{% endfor %}
CompetitionEntry.objects.filter(...).annotate(vote_count=Count('competitionentryvote', distinct=True))
.annotate(likes_count=Count('entrylikes', distinct=True))