在 Django DetailView 中引用外键

Reference ForeignKey in Django DetailView

我很难从 Django 中的基本 DetailView 引用我的 ForeignKey。

我正在使用的models.py:

class Posts(models.model):
    url = models.URLField()
    

class Comment(models.model):
    post = models.ForeignKey(Posts, related_name='comments', on_delete=models.CASCADE)
    content = models.CharField(max_length=500, blank=False)

views.py:

class PostDetailView(DetailView):
    model = Posts
    context_object_name = 'posts'

我正在尝试引用我的 post 详细信息页面中的评论。

posts_details.html:

{% for comment in posts.comments.all %}
  {{comment.content}}
{% endfor %}

我也尝试过将 posts.comments.all 更改为 posts.comments_set.all,但仍然没有结果。

我觉得我缺少的是一些小东西,但我想不通。

数据是有的,用外键引用输入正确,但我无法通过详细视图引用它。


编辑答案:

通过将此添加到评论模型,我能够相当简单地使其工作:

def get_absolute-url(self):
    return reverse('post_detail', kwargs={'pk': self.post.pk})

这让我可以通过以下循环访问 post_detail.html 中的 post:

{% for comment in posts.comments.all %}
    {{comment.content}}
{% endfor %}

您的帖子模型没有评论字段...因此 posts.comments.all 始终为空。不幸的是,如果您尝试访问模板标签中不存在的字段,您不会收到错误消息

class Posts(models.model):
    url = models.URLField()
    
    def get_all_comments(self):
        return Comment.objects.filter(post=self.pk)

使用此方法,将返回的查询集添加到上下文中。