gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:27:46 25 4
gpt4 key购买 nike

这是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. 这里的问题是输出中的投票和点赞都是相同的。i,e 投票=喜欢=喜欢

  2. 如果我重写 View 以仅显示投票或点赞之一,则该页面可以完美运行。

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

最佳答案

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

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

If distinct=True, the count will only include unique instances. This is the SQL equivalent of COUNT(DISTINCT ). The default value is False.

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

关于django - QuerySet,在多个字段上使用 annotate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16778734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com