How to pass extra context to Django Rest Framework serializers

前端 未结 2 1843
情歌与酒
情歌与酒 2020-12-04 04:14

It is my first project using Django rest framework and i\'m struggling to get this right. I know that in mainstream Django framework, if i need to add extra contexts to a cl

2条回答
  •  眼角桃花
    2020-12-04 04:27

    You have to use get_object as func, not as property:

    class PostViewSets(viewsets.ModelViewSet):
        queryset = Post.objects.all()
        serializer_class = PostSerializer
    
         def get_serializer_context(self):
            context = super(PostViewSets, self).get_serializer_context()
            author = self.get_object().author
            author_posts = self.get_queryset().filter(author=author)
            context.update({'author_posts': author_posts})
            return context
    

提交回复
热议问题