使用过滤器将对象传递到详细信息视图(Django)

Passing objects to Detail View with filter (Django)

我正在尝试将评论查询(评论模型)传递给 Post 模型的 DetailView,使用过滤器在 DetailView 中仅获取与特定 post.

相关的评论

Post 型号:

class Post(models.Model):
    title = models.CharField(max_length=300)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

评论模型:

class Comment(models.Model):
    content = models.CharField(max_length=500, help_text='Не более 500 знаков')
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(on_delete=models.CASCADE)
    post_id = models.ForeignKey(on_delete=models.CASCADE)

详情查看:

class PostDetailView(DetailView):
    context_object_name = 'post'
    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.filter(post_id = self.model.id)
        return context

它returns类型错误:

int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'

您能否就如何正确使用过滤器获取与此 Post 相关的仅 DetailView 评论提供建议?谢谢!

这里你的 self.model 将 return Post(对模型 class 的引用),而不是 post 对象。

您可以使用 self.object 访问对象,如 documentation:

中指定

While this view is executing, self.object will contain the object that the view is operating upon.

class PostDetailView(DetailView):
    context_object_name = 'post'
    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.filter(post_id=self.<b>object</b>)
        return context

你也可以利用颠倒的关系,比如:

class PostDetailView(DetailView):
    context_object_name = 'post'
    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = <b>self.object.comment_set.all()</b>
        return context

Note: note that a ForeignKey field typically does not end with an _id suffix, Django will automatically add an extra field named fieldname_id, so here you have two fields, post_id, and post_id_id, which is quite strange.