python - Django 模型序列化器

标签 python django python-2.7 django-rest-framework

我正在使用django-rest-framework - 我想重命名(在列表中)模型序列化器中的字段,并使用我在列表中重命名(更新)的相同名称进行更新。

class ConfiglistSerializer(serializers.ModelSerializer):

    class Meta:
        model = Config
        fields = ('id', 'configname', 'mac_address')
    def to_representation(self, obj):
        return {
            'id': obj.id,
            'configname': obj.name,
            'macAddress': obj.mac_address
        }

如何使用 putpatch 中的名称 ("configname", "macAddress") 进行更新?

最佳答案

您必须使用驼峰式大小写的解析器和渲染器:

$ pip install djangorestframework-camel-case

并将渲染和解析器添加到您的 django 设置文件中。

REST_FRAMEWORK = {

    'DEFAULT_RENDERER_CLASSES': (
        'djangorestframework_camel_case.render.CamelCaseJSONRenderer',
        # Any other renders
    ),

    'DEFAULT_PARSER_CLASSES': (
        'djangorestframework_camel_case.parser.CamelCaseJSONParser',
        # Any other parsers
    ),
}

这样您就可以在序列化器中使用snake_case,并在API中使用camelCase,而无需自定义to_representation方法

关于python - Django 模型序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45812314/

相关文章:

Python 变量赋值

python - 使用 root 权限部署 Flask 应用程序

python - 连接 ListView 和详细 View -django

c - Python C API : Passing two functions of many parameters with special types as module

python - 无法从字节转换为 int

python - Vim PEP-8 插件的配置设置以忽略错误和警告?

python - 为什么要使用三个迁移命令才能成功迁移数据库?

django - 在中间件中设置要在模板中访问的变量

python-2.7 - SQLAlchemy 事务中的错误不会返回正确的回溯(Python 2.7)

python - python 获取不匹配的行号