Django序列化器字段值基于同一序列化器中的其他字段

Pan*_*ang 5 python django serialization django-rest-framework

假设我有以下序列化程序。

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']
Run Code Online (Sandbox Code Playgroud)

get_commented方法中的编码有什么建议吗?我编写了类似return comment_count > 0但失败的代码。

Rap*_*aud 3

您可以使用 obj 访问 django 对象,所以我认为代码将类似于:

obj.comment_set.count()
Run Code Online (Sandbox Code Playgroud)

获取评论数,然后:

return self.get_comment_count(obj) > 0
Run Code Online (Sandbox Code Playgroud)

正如 Pang 所说,要实现 get_commented