2013-05-27 138 views
0

这种使用注释()是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

+0

我从上面的models.py和views.py中删除了内容,因为它们太大而无法粘贴。希望这不会消除主要问题。 –

回答

1

Count骨料作品映射到SQL COUNT()表达。请参阅the documentation here

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

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

I.e.

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

对不起,我没有明白这一点(我只有SQL的基本知识)。那么在这里包括这两个数字是不可能的? –

+0

您是否尝试过我建议的代码示例?它有用吗? – Krumelur

+0

好的,会尝试的 –