Pang
Pang

Reputation: 532

Django serializer field value base on other field in the same serializer

Suppose I have the following serializer.

class ArticleSerializer(serializers.ModelSerializer):    
    comment_count = serializers.SerializerMethodField()
    commented = serializers.SerializerMethodField()
    def get_comment_count(self, obj):
        # Assume the method can retrieve the comment count correctly
        return x
    def get_commented(self, obj):
        # Return True if comment count > 0, else False
    class Meta:
        model = Article
        fields = ['title', 'content', 'comment_count', 'commented']

Any suggestions for the coding in get_commented method? I code something like return comment_count > 0 but fail.

Upvotes: 6

Views: 3073

Answers (1)

Raphaël Braud
Raphaël Braud

Reputation: 1519

You can access the django object using obj, so I think the code will be something like :

obj.comment_set.count()

to get the comment count and then :

return self.get_comment_count(obj) > 0

as Pang said to implement get_commented

Upvotes: 3

Related Questions