Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use count() in serializers?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

class ArticleSerializer(serializers.ModelSerializer):
    # …

    def get_total_likes(self, language):
        return language.articlelikes.count()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading