如何连接相关对象并在模板中呈现它们?

时间:2017-01-06 21:46:39

标签: django django-templates django-orm

我有相关的模型:

public class MyBarChartRenderer extends BarChartRenderer {

    //TODO: a constructor matching the superclass

    @Override
    public void drawValues(Canvas c) {
        //TODO: copy and paste the code from the superclass and simply
        //change the offset for drawing the labels
    }
}

我的问题是如何在模板中列出所有民意调查及其各自的选择。

我现在拥有的ORM查询是:

class Poll(models.Model):
    creator = models.ForeignKey(User, blank=True, null=True)
    title = models.CharField(max_length=300)
    pub_date = models.DateTimeField('date published')
    published = models.BooleanField(default=True)


class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=300)
    votes = models.IntegerField(default=0)

在模板中:

polls = Choice.objects.select_related('poll') 

但是这个解决方案只列出了选择。我想要的是呈现与每个民意调查相关的选择。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

查询集:

polls = Polls.objects.all() # Give you all polls

模板:

{% for p in polls %}
    <p>Poll :{{ p.title }}</p>
    <ul>
    {% for choice in p.choice_set.all %}
       <li>{{ choice.choice_text }}</li>
    {% endfor %}
    </ul>
{% endfor %}

如果我理解你的问题,我希望这会对你有所帮助