Django 子模型不出现在模板中

Django sub models do not appear in template

可能是树多见不见林,但我有一个很奇怪的问题。

views.py:

from django.shortcuts import render
from models import Question, QuestionAnswerAlloc, Section

def home(request):
    sections = Section.objects.all()
    for s in sections:
        questions = Question.objects.filter(section=s)
        for q in questions:
            answersalloc = QuestionAnswerAlloc.objects.filter(question=q)
            q.answers.append(answersalloc)
        s.questions.append(questions)

    return render(request, "questionaire/index.html", {'sections': sections})

models.py:

from django.db import models

from portal.models import Customer


class Section(models.Model):
    title = models.CharField(max_length=150)
    weight = models.FloatField()
    maxscore = models.FloatField()

    questions = []

    def __unicode__(self):
        return "%s" % (self.title)


class Question(models.Model):
    title = models.TextField()
    section = models.ForeignKey(Section)
    weight = models.FloatField()

    answers = []

    def __unicode__(self):
        return self.title


class Answer(models.Model):
    title = models.CharField(max_length=150)
    points = models.IntegerField(default=0, help_text="This has to be a value between 0 and 5")
    is_weighted = models.BooleanField(default=True, help_text="If this answer does not apply (N/a) it is not weighted!")

    def __unicode__(self):
        return self.title


class QuestionAnswerAlloc(models.Model):
    question = models.ForeignKey(Question)
    answer = models.ForeignKey(Answer)

    def __unicode__(self):
        return "Possible Answer"


class Report(models.Model):
    STATUS_STARTED = "started"
    STATUS_FIN = "finished"
    STATUS_INPROG = "inprogress"
    STATUS_ABORT = "aborted"

    date = models.DateField(auto_now_add=True, blank=True)
    title = models.CharField(max_length=150)
    started_time = models.DateTimeField()
    end_time = models.DateTimeField()
    status = models.CharField(max_length=150, default=STATUS_STARTED)
    guid = models.CharField(max_length=150, unique=True)

    def __unicode__(self):
        return self.title


class ReportAnswer(models.Model):
    title = models.CharField(max_length=150)

    orignal_answer = models.ForeignKey(Answer)
    question = models.ForeignKey(Question)
    section = models.ForeignKey(Section)
    report = models.ForeignKey(Report)

    points = models.FloatField()
    weight = models.FloatField()
    is_weighted = models.BooleanField(default=True)

    customer = models.ForeignKey(Customer, blank=True, null=True)

    def __unicode__(self):
        return self.title

还有我的模板:

{% for s in sections %}
            <div class="row">
                <div class="col-sm-12">
                    <div class="FormStepInfo">
                        <p class="QuestionaireSectionTitle">{{s.title}}</p>
                        <p class="QuestionaireSectionDesc"></p>
                    </div>
                </div>
            </div>

                {% for q in s.questions %}
                <div class="row">
                    <hr/>
                    <div class="col-sm-2 quest-num">{{forloop.counter }}</div>
                    <div class="col-sm-10 quest-title">
                        <label>
                            {{q.title}}
                        </label>
                        <br/>

                        <div class="CheckboxQuestion">
                            {% for a in q.answers %}
                            <label for=""><input type="radio" name="Q3" value="{{a.points}}" id="q3a1">{{a.title}}</label>
                            {% endfor %}
                        </div>
                    </div>
                </div>
                {% endfor %}
            {% endfor %}

很遗憾,问题标题和答案均未显示。 如果我打印到 sys.stderr,我可以看到有分配给该部分的问题。我错过了什么吗?我已经重新启动了我的 "webserver",因为我使用了 "python manage.py runserver" 大约 10 次并删除了我的缓存。

你对Python中的class定义有较大的误解。通常,当您在 class 级别定义一个属性时,它会被 class 的所有成员共享。 Django 字段做了一些特殊的魔法来确保值是每个实例而不是每个 class,但是您的 questionsanswers 列表不会这样做。因此,即使您可以让您的代码正常工作,所有答案也会与所有问题相关联。

幸运的是,无需执行任何这些操作。 Django 为您提供了恰好满足您需求的反向访问器。所以视图可以简化为:

def home(request):
    sections = Section.objects.all()
    return render(request, "questionaire/index.html", {'sections': sections})

视图变为:

{% for s in sections %}
   ...
   {% for q in s.question_set.all %}
       ...
       {% for a in q.questionansweralloc_set.all %}

       ...etc