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
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
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
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.