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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With