我已经编辑了教程中的代码,使索引视图看起来像这样:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
"""
Return the last five published polls (not including those set to be
published in the future, or those without choices).
"""
return Poll.objects.filter(
pub_date__lte=timezone.now(), choice__choice_text__isnull=False
).order_by('-pub_date')[:5]
但是现在我的索引看起来像这样:
这是怎么发生的?我该如何解决这个问题?
(ps.我不知道该由谁使用过滤器,所以我从这个question复制了代码。这就是它不起作用的原因吗?双下划线
__
符号如何在过滤器中工作?)
编辑:我已经检查了管理视图,数据库中的每个民意调查似乎只有一个(我没有直接检查),但我相信它的设置方式我不能有多个具有相同 ID 的民意调查(在这种情况下,所有“你在做什么?”民意调查的 ID 为 2,所有“怎么了?”民意调查的 ID 为 1)。
将
distinct()
(如Wolf建议)添加到方法链中确实有效。我认为问题的关键在于,最终的数据库查询返回最近的民意调查 (pub_date__lte=timezone.now()
) 和具有非空选择的民意调查 (choice__choice_text__isnull=False
) 的组合,无论重叠如何。
我不确定除了使用
distinct()
事实证明,不同的是正确的解决方案:
“我搜索了解释,看起来当查询跨越多个表时,它可以返回重复项。distinct 是这里正确的解决方案。”
– Ludovic Viaud 在评论