Home > Net >  How to use count() in serializers?
How to use count() in serializers?

Time:12-11

I am trying to get count of article likes,but the problem is that i am facing with various errors. Here is my code:

class ArticleLikeSerializer(serializers.ModelSerializer):

    class Meta:
        model = ArticleLike
        fields = ('id',"author","article",'timestamp')

class ArticleSerializer(serializers.ModelSerializer):
    articlelikes_set = ArticleLikeSerializer(source='articlelikes',required=False,many=True)
    total_likes = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Article
        fields = ('id','author','caption','total_likes','articlelikes_set')

    def get_total_likes(self, language):
        return articlelikes_set.count()

Here is my error:

name 'articlelikes_set' is not defined

How can i solve the problem?

CodePudding user response:

language is the object you are serializing, hence you return:

class ArticleSerializer(serializers.ModelSerializer):
    # …

    def get_total_likes(self, language):
        return language.articlelikes.count()
  • Related