Django:如何将评论与HTML模板中相应的OP相关联?

时间:2014-09-09 05:17:45

标签: python html django django-views

我设计了一个简单的发布和评论系统,其中每个postcomment对象使用外键与其对应的newpost对象相关联。我的问题是模板中的注释没有显示在相应的newpost对象下。例如,如果每个帖子下总共有3个新帖子和3条评论共9条评论,则模板会在每3个帖子下显示所有9条评论(总共27条评论)。我需要帮助找出如何正确地将每个评论与其相应的帖子相关联,而不是仅仅遍历每个帖子下的“allcomments”字段。感谢您的帮助和提示。

postset = pagename.newpost_set.all().order_by('-postdate') #i use this to get a queryset of all posts on the selected page and order them so newest posts show up at the top
allposts = newpost.objects.filter(newposttag=‘userpage’) #i use this to get a queryset of all posts on the corresponding user’s page for the next line, this might seem redundant after the above, but it works because the postset is what I end up using in the template. 
 allcomments = postcomment.objects.filter(commenttag=allposts) #i use this to get a queryset of all the comments from each post in the ‘allposts’ queryset 

这是我用于显示我已获得的上述信息的模板

{% for postset in postset %}
    <br>{{ postset.postcontent }} {{postset.postdate }} - {{ postset.postlikes }} likes <a href="/enterlink/comment">Comment</a></br>
    {% for allcomments in allcomments %}
    <br> {{ allcomments.comment }} {{allcomments.postcommentdate }} - {{ allcomments.commentlikes}}
{% endfor %}
{% endfor %}

1 个答案:

答案 0 :(得分:1)

如何更新模板如下:

{% for post in postset %}
    <br>{{ post.postcontent }} {{post.postdate }} - {{ post.postlikes }} likes <a href="/enterlink/comment">Comment</a></br>

    {% for comment in post.postcomment_set.all %}
        <br> {{ comment.comment }} {{comment.postcommentdate }} - {{ comment.commentlikes}} </br>
    {% endfor %}
{% endfor %}

这样,您可以迭代帖子,对于每篇帖子,您可以通过post.postcomment_set.all表达式检索与该帖子相关的评论。

如果有帮助,请告诉我。

ps:我不认为您在视图中需要这三个查询。