I am creating my first django API with django-rest-framework. I have a list of Posts. Each post can have many Likes. Therefore, I have added a ForeignKey to the Like model, which points to its corresponding Post.
When I retrieve the information of a post, I'd like to get the number of likes that this post has.
Here is my url:
path(BASE_URL + "get/slug/<slug:slug>", GetPost.as_view()),
This is my view:
class GetPost(generics.RetrieveAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
lookup_field = "slug"
And this is my serializer:
class PostSerializer(serializers.ModelSerializer):
likes_amount = serializers.SerializerMethodField(read_only=True)
def get_likes_amount(self, post):
return post.likes
class Meta:
model = Post
fields = '__all__'
Unfortunately, as soon as I add the extra property likes-amount to the serializer, the API endpoint stops working and I get the following error: Object of type RelatedManager is not JSON serializable.
I'd like to know how I can extend the ModelSerializer with extra fields like the number of likes of my Post, so that I can get. I have read the documentation but haven't found any information on that topic.