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

时间:2018-11-24 15:36:17

标签: django filtering detailview

我正在尝试使用过滤器将评论查询(评论模型)传递给Post模型的DetailView,以仅获取与微粒帖子相关的DetailView评论。

发布模型:

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

它返回TypeError:

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

请提供有关如何正确使用过滤器以仅获取与本帖子相关的DetailView注释的建议,请提供帮助?谢谢!

1 个答案:

答案 0 :(得分:2)

在这里,您的self.model将返回Post(对模型类的引用),而不是post对象。

您可以使用documentation中指定的self.object访问对象:

  

该视图正在执行时, self.object将包含该视图正在操作的对象

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.object)
        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'] = self.object.comment_set.all()
        return context
  

注意:请注意,ForeignKey字段通常不是_id后缀结尾,Django会自动添加一个名为{ {1}},因此这里有两个字段fieldname_idpost_id,这很奇怪。