2013-04-26 71 views
2

我有模型與用戶,問題和答案。現在我想顯示哪些用戶回答的問題。在模板查詢與值不同,mysql,django

answers = Answer.objects.filter(author__username=user.username)[:5] 

這:

我在views.py寫這篇

{% for answer in answers %} 
{{ answer.question.head }} <hr> 
{% endfor %} 

而且我看到2個問題,在年底小時管線重複5次。我希望看到2個問題,即使用戶回答5倍至2個回答,讓我試試這個:

answers = Answer.objects.filter(author__username=user.username).values('question__head').distinct()[:5] 

但是,當我打開我的網頁我看只有兩個小時線,由於某種原因,沒有內容。 我試圖ORM和它工作正常

>>> Answer.objects.filter(author__pk=2).values('question__head').distinct() 
[{'question__head': u'question1?'}, {'question__head': u'question2?'}] 

爲什麼{{answer.question.head}}沒有模板添加不同的條件後工作了?

+0

做'mysql'支持'明顯的()'? – 2014-03-30 22:37:06

回答

0

好了,終於我用下面的代碼片段解決了這個問題:

#views.py 
answers = Answer.objects.filter(author__username=user.username).values_list('question__head', flat=True).distinct()[:5] 

#template 
{% for answer in answers %} 
{{answer}} 
{% endfor %}