0

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.

0

1 Answer 1

1

post.likes returns a queryset with related models. if you want the count of likes use count() on that queryset.

def get_likes_amount(self, post):
    return post.likes.count()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.