所以我需要使用一个 API 来说明 JSON 字段都是驼峰,我想将它们作为snake_case写在我的代码上。我该怎么做?
我想要这样的东西:
serializer = MySerializer(data={'my_field': 'test'})
if serializer.is_valid():
output_data = serializer.validated_data
print(output_data)
# {'myField': 'test'}
Vitaly Babiy的djangorestframework-camel-case正是这样做的: https://github.com/vbabiy/djangorestframework-camel-case 你必须像这样用 settings.py 提到它:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'djangorestframework_camel_case.render.CamelCaseJSONRenderer',
'djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer',
# Any other renders
),
'DEFAULT_PARSER_CLASSES': (
# If you use MultiPartFormParser or FormParser, we also have a camel case version
'djangorestframework_camel_case.parser.CamelCaseFormParser',
'djangorestframework_camel_case.parser.CamelCaseMultiPartParser',
'djangorestframework_camel_case.parser.CamelCaseJSONParser',
# Any other parsers
),
}
它可以工作,无需更改序列化程序。