有没有一种方法可以将模型的行循环到表中。如果我可以排除某些字段,这也将非常有用。我正在制作一个用户可以创建的表格,方法是在一个模型中创建要问的问题,然后在模型中寻找答案
例如:
模型
class Questions(models.Model):
name = models.Charfield()
Question1 = models.Charfield()
Question2 = models.Charfield()
ect
class Answers(models.Model):
question = models.ForeignKey(Questions, related_name='question')
qustion_no = models.IntegerField()
answer = models.Charfield()
form.html
<table>
<tr>
<th>Question</th>
<th>Answers</th>
</tr>
{% for q in Questions %}
<tr>
<td>{{q}}</td>
<td>{{q.question}}</td
</tr>
{% endfor %}
</table>
最佳答案
我想您可能正在寻找类似的东西。
<table>
<tr>
<th>Question</th>
<th>Answers</th>
</tr>
{% for q in Questions %}
<tr>
{% for a in q.question.all %}
<td>{{q}}</td>
<td>{{a.answer}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>