Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 731
Pang Avatar asked Oct 20 '22 15:10

Pang


1 Answers

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

like image 70
Raphaël Braud Avatar answered Oct 30 '22 20:10

Raphaël Braud