How to pass extra context to Django Rest Framework serializers

前端 未结 2 1837
情歌与酒
情歌与酒 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
    
    0 讨论(0)
  • 2020-12-04 04:39

    1. The Error Message

    AttributeError at /posts/ 'function' object has no attribute 'author'

    explicitly explains what and where is the problem:

    author = self.get_object.author

    I guess you tried to do something like this

    author = self.get_object().author
    

    2. A DRF ViewSet

    responses with data serialized by corresponding Serializer. So you don't need to change the ViewSet, but update the Serializer with something like:

    class PostListSerializer(serializers.ModelSerializer):
        ... some fields ...
    
        class Meta:
            model = Post
            fields = [ ... some fields ... ]
    
    
    class PostDetailsSerializer(serializers.ModelSerializer):
        ... some fields ...
    
        author_posts = PostListSerializer(source="author.post_set", many=True, read_only=True)
    
        class Meta:
            model = Post
            fields = [ ... some fields ... , 'author_posts']
    

    or with SerializerMethodField

        class PostDetailsSerializer(serializers.ModelSerializer):
        ... some fields ...
    
        author_posts = serializers.SerializerMethodField()
    
        def get_author_posts(self, obj):
            return PostListSerializer(instance=obj.post_set.all(), many=True).data
    
        class Meta:
            model = Post
            fields = [ ... some fields ... , 'author_posts']
    

    I didn't try this exact code, but this is the main idea.

    0 讨论(0)
提交回复
热议问题