class PostSerializer(serializers.ModelSerializer):
categories = serializers.StringRelatedField(many=True)
comments_count = serializers.SerializerMethodField()
class Meta:
model = Post
fields = ('id', 'title', 'body', 'categories', 'comments_count')
def get_comments_count(self, obj):
return obj.comments.count()