将模型字段序列化为嵌套对象/字典 [英] Serialize model fields into nested object/dict
问题描述
想象一下以下模型:
class Person(models.Model):
name = models.CharField()
address_streetname = models.CharField()
address_housenumber = models.CharField()
address_zip = models.CharField()
我有一个django rest框架ModelSerializer
,它公开了所有字段.
但是我希望能够将地址字段序列化为字典.因此,当序列化为json输出时,将是:
I have a django rest framework ModelSerializer
that exposes all the fields.
But I would like to be able to serialize the address fields into a dict. So when serialized to json output would be:
{
name: 'Some name',
address: {
streetname: 'This is a test',
housenumber: '23',
zip: '1337',
}
}
我尝试创建创建AddressSerializer
class Address(object):
...
class AddressSerializer(serializers.Serializer):
streetname = serializers.CharField()
housenumber = serializers.CharField()
zip = serializers.CharField()
...
,然后将PersonSerializer.address
设置为使用AddressSerializer
class PersonSerializer(serializers.ModelSerializer):
...
address = AddressSerializer()
这导致我的架构正确.我使用drf-yasg
生成了大张旗鼓的文档.它查看序列化器以生成正确的模型定义.因此,序列化程序需要表示模式.
This results in my schema being correct. I generate swagger docs by using drf-yasg
. It looks at the serializers to generate the correct model definitions. So the serializers needs to represent the schema.
这就是我现在的位置.显然现在失败了,因为Person
模型中没有address
属性.您将如何解决这个问题?
So this is where I am at, at the moment. Obviously now it fails because there is no address
property in the Person
model. How would you go about solving this?
推荐答案
noreferrer>用于source
的DRF文档说,
from the DRF-doc for source
says,
值
source='*'
具有特殊含义,用于表示 应该将整个对象传递给该字段.这个可以 对于创建嵌套表示或对于其中的字段很有用 需要访问完整的对象才能确定输出 表示形式.
The value
source='*'
has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
所以,尝试一下,
So,try this,
class AddressSerializer(serializers.Serializer):
streetname = serializers.CharField(source='address_streetname')
housenumber = serializers.CharField(source='address_housenumber')
zip = serializers.CharField(source='address_zip')
class PersonSerializer(serializers.ModelSerializer):
# .... your fields
address = AddressSerializer(source='*')
class Meta:
fields = ('address', 'other_fields')
model = Person
这篇关于将模型字段序列化为嵌套对象/字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!