class Thread(models.Model):
question = models.TextField()
# you can add other fields
class Answer(models.Model):
thread = models.ForeignKey(Thread, on_delete=models.CASCADE, related_name='thread_ans')
answer = models.TextField()
if_correct = models.BooleanField()
# you can add other fields
视图.py
def quest(request):
q1 = Answer.objects.filter(if_correct=True).select_related('thread') # if you want only correct answer in template
q2 = Thread.objects.all().prefetch_related('thread_ans') # For all answers
conext = {
'q1': q1,
'q2': q2,
}
在模板中
# <! For Question and correct answer >
{% for i in q1 %}
<p>Ques: i.thread.question</p>
<p>Ans: i.answer</p>
{% endfor %}
# <! For Question and all answers with correct or incorrect >
{% for i in q2 %}
<p>Ques: i.question</p>
{% for j in i.thread_ans.all %}
<p>j.answer</p> # <! Print answer ->
<p>j.is_correct</p> # <! Print if correct or not ->
{% endfor %}
{% endfor %}
使用筛选器标记显示3条注释,https://docs.djangoproject.com/en/2.2/ref/templates/builtins/ 您可以在自定义筛选器标记中找到每个线程的最新3个答案,如下所示
如果您的models.py如下所示:
视图.py
在模板中
相关问题 更多 >
编程相关推荐