鉴于我正在编写代码的 OpenAPI 规范需要在请求正文中使用连字符大小写(又名短横线大小写)变量名称,那么在使用 Django Rest Framework 时应如何处理?
例如,一个请求POST /thing
创建一个具有以下主体的事物:
{
"owner-type": "platform"
}
但在Python中,owner-type
不是有效的变量名称(“SyntaxError:无法分配给运算符”),因此Thing
has owner_type
在模型定义中:
class Thing(models.Model):
owner_type = models.CharField(max_length=8)
但现在ThingSerializer
是有问题的,因为,再一次,owner-type
是非法名称。这是不允许的:
owner-type = serializers.CharField(...)
我试图覆盖名称的生成方式ModelSerializer
通过尝试调整生成的字段名称get_fields()
,但失败了。这是我的序列化器:
class ThingSerializer(serializers.ModelSerializer):
class Meta:
model = Thing
fields = [
'owner_type',
]
def get_fields(self):
fields = super().get_fields()
out_fields = OrderedDict()
for field_name, field in fields.items():
out_fields[field_name.replace('_', '-')] = field
return out_fields
和错误:
../venv/lib/python3.6/site-packages/rest_framework/fields.py:453: in get_attribute
return get_attribute(instance, self.source_attrs)
../venv/lib/python3.6/site-packages/rest_framework/fields.py:101: in get_attribute
instance = getattr(instance, attr)
E AttributeError: 'Thing' object has no attribute 'owner-type'
所以我的问题是 - 如何配置 DRF 模型序列化器以允许对包含下划线的模型字段进行序列化/反序列化,以便 API 客户端看到连字符而不是下划线?这将是上面示例的通用解决方案,其中Thing.owner_type
应该通过传递字段来读取/写入"owner-type"
在 JSON 正文中。
我在 Python 3.6 上使用最新的 Django 和 DRF。
编辑 1:澄清理想情况下这将是一个将下划线转换为连字符的通用解决方案。