Django查询多对一关系

时间:2011-04-18 15:39:04

标签: django django-models

我有三个模型,一个主题可以有零个或多个问题,一个问题可以有零个或多个答案。只有一个答案是正确的。

他们是多对一的关系。

class Topic(models.Model):

class Question(models.Model):
    topic = models.ForeignKey(Topic)

class Answer(models.Model):
    question = models.ForeignKey(Question) 
    isright = models.BooleanField(verbose_name='Right')

现在我尝试根据主题循环问题,如何使用模板实现它?

<topic>

  <question>
    <answer>
    <answer>
    <answer>
    <answer>

  <question>
    <answer>
    <answer>
    <answer>
    <answer>

如何为问题添加分页器?

paginator = Paginator(topic.question_set.all(), 25) 

3 个答案:

答案 0 :(得分:5)

如果我理解得很好,你想要循环“主题”排序的答案:

answers = Answer.objects.order_by('question__topic', 'question')

或:

for topic in Topic.objects.all():
    for question in topic.question_set.all():
        for answer in question.answer_set.all():
            ...do something...

在模板中,您可以执行相同操作,将变量topics作为Topic.objects.all():

{% for topic in topics %}
    {% for question in topic.question_set.all %}
        {% for answer in question.answer_set.all %}
            ...do something...
        {% endfor %}
    {% endfor %}
{% endfor %}

答案 1 :(得分:1)

使用* _set.all()变量:

 t = Topic.objects.get(id=X)
 questions = t.question_set.all()

 for q in questions:
     answers = q.answer_set.all()

     for a in answers:
          print a

答案 2 :(得分:0)

topic_instance.question_set.all()

请参阅docs