2013-12-10 68 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