2013-12-10 69 views
1

我在寫我的第一個django應用程序,似乎無法通過ListView將「行級」數據傳遞給模板。具體來說,我試圖使用PollListView顯示所有投票和相應的投票信息。ListView中額外的「行級」數據django

目前我只能通過所有投票到模板,但只想通過屬於特定投票的投票。

models.py

class Poll(models.Model): 
    user = models.ForeignKey(User, unique=False, blank=False, db_index=True) 
    title = models.CharField(max_length=80) 

class Vote(models.Model): 
    poll = models.ForeignKey(Poll, unique=False, blank=False, db_index=True) 
    user = models.ForeignKey(User, unique=False, blank=True, null=True, db_index=True) 
    vote = models.CharField(max_length=30, blank=False, default='unset', choices=choices) 

views.py

class PollListView(ListView): 
    model = Poll 
    template_name = 'homepage.html' 
    context_object_name="poll_list" 

    def get_context_data(self, **kwargs): 
     context = super(PollListView, self).get_context_data(**kwargs) 
     context['vote_list'] = Vote.objects.all() 
     return context 

urls.py

urlpatterns = patterns('', 
... 
    url(r'^$', PollListView.as_view(), name="poll-list"), 
} 

homepage.html

{% for poll in poll_list %} 
    {{ poll.title }} 
    {% for vote in vote_list %} 
    {{ vote.id }} {{ vote.vote }} 
    {% endfor %} 
{% endfor %} 

看起來像一件容易的事,但我似乎無法弄清楚如何使用基於類的意見,做到這一點。我應該使用mixins還是extra_context?覆蓋queryset?或者我應該使用基於功能的視圖來解決這個問題。

任何幫助將不勝感激。

+0

什麼錯誤? –

+0

您要求提供所有投票。你應該使用'Vote.objects.filter(poll = instance)'我想。 –

+0

@RobL我沒有收到任何錯誤,因爲我得到的每個投票都返回了所有投票。因此,如果每個民意調查有1票,我有3個民意調查,我得到民意調查 - 3票,民意調查 - 3票,民意調查 - 3票。 – Darth

回答

2

我不知道這是否會工作,但你可以嘗試以下方法:

models.py(投票類)

poll = models.ForeignKey(Poll, related_name="votes", unique=False, blank=False, db_index=True) 

views.py

class PollListView(ListView): 
    queryset = Poll.objects.all().prefetch_related('votes') 

與那個你可以訪問相關的投票:

模板

{% for poll in poll_list %} 
    {{ poll.title }} 
    {% for vote in poll.votes.all %} 
    {{ vote.id }} {{ vote.vote }} 
    {% endfor %} 
{% endfor %} 
+0

謝謝你的答案我添加到ListView的查詢集沒有錯誤,但增益模板在模板中不可用我需要添加一個ManyToMany字段來輪詢這個工作 – Darth

+0

@Darth不,它使用反向關係也是如此。你是否從視圖中刪除了'model'屬性? – mariodev

+0

我刪除了模型屬性並且沒有運氣。我是否需要在某處定義「vote_set」?我應該覆蓋get_queryset方法還是在類中設置屬性定義足夠了嗎? – Darth