Skip to main content
 首页 » 编程设计

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

2024年10月25日33zhengyun_ustc

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

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'] 

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

请您参考如下方法:

您可以使用 obj 访问 django 对象,所以我认为代码应该是这样的:

obj.comment_set.count() 

获取评论数,然后:

return self.get_comment_count(obj) > 0 

如Pang所说的实现get_commented