python - 如何仅使用一个序列化器MethodField 获取两个值

标签 python django django-rest-framework

当'content'字段被排除时,我想在'sth'字段添加“NOT content contains”,否则“content contatined”

序列化器.py

class PostSerializer(serializers.ModelSerializer):
    sth = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('id', 'sth', 'content', 'created',)

    def get_sth(self, obj):
        return 

回复我想要得到的内容

[
    {
      "id": "1",
      "sth": "content contained",
      "content": "a",
      "created": "2020-01-23"
    },
    {
      "id": "3",
      "sth": "NOT content contained",
      "created": "2020-01-22"
    },
]

我怎样才能得到像上面这样的回复。

最佳答案

在您的 to_representation 方法中修改它,如下所示

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('id', 'content', 'created',)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if content is not included:
           data.update({'sth': "content contained"})
        else:
           data.update({'sth': "NOT content contained"})
        return data

您必须根据您的系统设置不包含内容条件。

关于python - 如何仅使用一个序列化器MethodField 获取两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59889844/

相关文章:

python - Django 仅在生产环境中使用私有(private) S3 存储

python - Boost.Python : Fill in a passed in buffer in Python

Python netaddr 在命中空 csv 单元格时抛出错误

python - 使用带有自定义用户模型和 UserManager 的 python-social-auth 创建 django 用户时出现问题

python - 检查模板 Django 中变量中字符串的某些部分

python - DRF 序列化程序中多个查找字段的自定义超链接 URL 字段

django - 我如何自动填充我的字段并使其在 django 管理站点中不可编辑

python - 如果父进程在 Python 中被杀死,则杀死子进程

python - 为什么我的示例 google api 代码(python、admin、directory_v1)上出现 503 服务不可用?

python - django 模板上传文件 - 如何处理不存在的物理文件