Python 将Django注释指向特定对象
在Django网站中,我无法将特定评论指向特定对象。在下面的HTML页面上,将显示5篇Python 将Django注释指向特定对象,python,django,Python,Django,在Django网站中,我无法将特定评论指向特定对象。在下面的HTML页面上,将显示5篇文章及其各自的属性。每个post都有自己的comment\u表单,用户可以在表单中留言。然而,当一条评论被留下时,所有的帖子共享相同的评论,而不是他们自己独特的评论集。有没有人建议我给每个帖子提供自己独特的评论集,这样他们就不会共享相同的评论 以下是我当前的HTML: <div class="mainContent"> <div class="content">
文章及其各自的属性。每个post
都有自己的comment\u表单
,用户可以在表单中留言。然而,当一条评论被留下时,所有的帖子共享相同的评论,而不是他们自己独特的评论集。有没有人建议我给每个帖子
提供自己独特的评论集
,这样他们就不会共享相同的评论
以下是我当前的HTML:
<div class="mainContent">
<div class="content">
{% for post in posts %}
<article class="topContent">
<div>
<h1>{{ post.title }}</h1>
<p>{{ post.body }}</p>
<h6><i>published {{ post.pub_date }}</i></h6>
<div class="commentForm">
{% for comment in comments %}
<p id="commentP">{{ comment.comment }} - {{ comment.name }}</p>
{% endfor %}
</div>
<form method="POST" action="">
{% csrf_token %}
<div id='comment_form'>
<div id="namePrompt">
<p> Name:</p>
</div>
<div id="formName">
{{form.name}}
</div>
<div id="commentPrompt">
<p> Comment: </p>
<div id="formComment">
{{form.comment}}
</div>
<div id="submitBtn">
<input type='submit' name='submit' value='Add Comment'>
</div>
</div>
</form>
</div>
</article>
{% endfor %}
</div>
</div>
如果一篇文章和它的相关评论之间没有关联,那么每次查询数据库时,都会得到所有评论并将其传递给模板
正如您在自己的评论中提到的,在评论
模型上添加一个foreignkey应该可以工作。因此,当您查询某篇文章的评论时,您应该只能查询与该文章相关的评论
所以本质上是这样的:
class ProjectPosts(models.Model):
....
class ProjectComments(models.Model):
....
post = models.ForeignKey(ProjectPosts)
post_comment = PorjectPosts.projectcomments_set.filter(id=foo)
在检索与帖子相关的所有评论时,您可以执行以下操作:
class ProjectPosts(models.Model):
....
class ProjectComments(models.Model):
....
post = models.ForeignKey(ProjectPosts)
post_comment = PorjectPosts.projectcomments_set.filter(id=foo)
您可以在中阅读更多关于关系的信息。我假设您的模型如下所示:
class ProjectPosts(models.Model):
....
class ProjectComments(models.Model):
....
post = models.ForeignKey(ProjectPosts)
然后在模板中,您需要执行以下操作:
<div class="commentForm">
{% for comment in post.projectcomments_set.all %}
<p id="commentP">{{ comment.comment }} - {{ comment.name }}</p>
{% endfor %}
</div>
{post.projectcomments\u set.all%中的注释为%s}
{{comment.comment}}-{{comment.name}
{%endfor%}
嗯。您可以像在模板中那样迭代反向FK关系
编辑:我现在看到你把所有的评论都放在你的视图中,这也不是针对某个特定的帖子。你不需要那样做。每当您需要显示特定帖子的评论时,请在模板中执行我在上面显示的操作。我是否可以创建一个Comment()模型,并使用ForeignKey将其绑定到ProjectPost()的主键(pk),然后使用Comment()作为ProjectCommentForm()的元类,并通过my views.py进行渲染?或者,如果这不起作用,还有更有效的方法吗?我明白了,这是完全有道理的。甚至不需要通过视图渲染它们,这非常好!谢谢你们的帮助