_set.all 列表中的每个项目

问题描述 投票:0回答:1

我有一个 Django 应用程序,其中有针对特定答案的评论。现在我想访问每个答案的评论并将其呈现到模板中。

模型.py

class Comment(models.Model):
    comment_text = models.TextField()
    user_id = models.ForeignKey(MyUser,blank=True)
    answer_id = models.ForeignKey(Answer, blank=True)
    comment_timestamp=models.DateTimeField(default=datetime.now())
    question_id = models.ForeignKey(Question, blank=True,null=True)
    anonymous_user=models.CharField(max_length=20,null=True)

在views.py中

answer = question.answer_set.all().order_by('-answer_timestamp')

给了我一个答案列表

[<Answer: It is a long established fact that a reader will be distracted by the .>, <Answer:It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.>]

现在我想访问每个答案的评论。 answer[0].set_all 、answer[1].set_all 是不可能的,因为可能还有更多答案。

我已经尝试过

{% for comment in ans.comment_set.all %}

{% endfor %}

在 django 模板中,但它没有给出所需的结果

任何其他方法,以便评论可以在views.py中的上下文中传递

django foreign-key-relationship
1个回答
0
投票

我知道那是几年前的事了。

{% for i in ans %}
    Answer = {{ i }} 

    Comments : - 
    {% for c in i.comment_set.all %}
        {{ c }} 
    {% endfor %}

{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.