我正在使用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
}
如何使用 put
或 patch
中的名称 ("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/