Django在索引页上显示帖子,每个帖子下都有少量答案(通过外键链接)

2024-09-19 14:32:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Django写一个Imageboard,但我无法解决这个基本问题:如何在主页上显示每个帖子的几个答案。我有两个模型,线程和答案,答案通过外键链接到线程。我想在下面展示每一个帖子,上面有三个最新的答案。我真的很想在这里得到一些帮助


Tags: django答案模型链接主页线程帖子外键
2条回答

使用筛选器标记显示3条注释,https://docs.djangoproject.com/en/2.2/ref/templates/builtins/ 您可以在自定义筛选器标记中找到每个线程的最新3个答案,如下所示

answers = Answer.objects.filter(Thread = Thread).order_by('date')[0:3]

如果您的models.py如下所示:

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 %}

相关问题 更多 >