[英]Unwrapping Compound Data with Django REST Framework Serializers
If I have a model that looks like this: 如果我有一个看起来像这样的模型:
class Subject(models.Model):
name_first = models.CharField(max_length=200)
name_middle = models.CharField(max_length=200, blank=True)
name_last = models.CharField(max_length=200)
name_prefix = models.CharField(max_length=200, blank=True)
name_suffix = models.CharField(max_length=200, blank=True)
favorite_color = models.CharField(max_length=200)
and I want to deserialize data that is sent as this: 我想反序列化以这种方式发送的数据:
"name": {
"prefix": "",
"first": "John",
"middle": "S",
"last": "Smith",
"suffix": ""
},
"favorite_color": "blue"
How do I do that in the Django REST framework? 如何在Django REST框架中做到这一点? I would prefer to not have to introduce a Name
model. 我希望不必引入Name
模型。
You could override the from_native
method on your serializer, modifying the data
dictionary so that it matches your model before the Django REST framework uses it to create an instance: 您可以在序列化程序上覆盖from_native
方法,修改data
字典,以使其在Django REST框架使用它创建实例之前与模型匹配:
class SubjectSerializer(serializers.ModelSerializer):
class Meta:
model = Subject
def from_native(self, data, files):
name_fields = data.pop('name', {})
for key, val in name_fields.items():
new_key = 'name_{0}'.format(key)
data[new_key] = val
return super(SubjectSerializer, self).from_native(data, files)
Note that this doesn't do any validation on the format of the incoming data, so depending on your situation you may need to guard against someone supplying something other than a dictionary. 请注意,这不会对传入数据的格式进行任何验证,因此,根据您的情况,您可能需要防止有人提供除字典以外的内容。 For example, the following data would cause an exception: 例如,以下数据将导致异常:
"name": "John Smith",
"favorite_color": "blue"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.