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

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

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

最佳答案

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

obj.comment_set.count()

获取评论数,然后:

return self.get_comment_count(obj) > 0

如Pang所说的实现get_commented

关于python - Django 序列化器字段值基于同一序列化器中的其他字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29295076/

相关文章:

Django:ModelChoiceField 删除默认值 --------- 选择

c# - 使用linq和automapper在dto中将属性序列化为复杂类型

javascript - 原始数据方法

.net - Protocol Buffer : Should I use int64 or fixed64 to represent a . NET DateTime 值?

python - 为 pyspark 中的唯一行生成序列列

python - 文件未找到错误: [Errno 2] No such file or directory: 'test_user1_user_id'

mysql - 如何使用单个 .csv 文件更新数据库(Django)中的多个表?

django - 如何制作同时执行 GET 和 POST 的 Django View ?

python - PermissionError Errno 13 权限被拒绝

python - 正则表达式:如何捕获其中包含空格的大数字?