所以如果我在Django中有以下模型类:
class Person(models.Model):
name = models.CharField(max_length=250)
is_active = models.BooleanField(default=True)
address_line1 = models.CharField(max_length=100, blank=True, null=True)
address_line2 = models.CharField(max_length=100, blank=True, null=True)
town = models.CharField(max_length=100, blank=True, null=True)
county = models.CharField(max_length=100, blank=True, null=True)
post_code = models.CharField(max_length=100, blank=True, null=True)
我的目标是将其序列化为以下JSON:
{
"name": "Joe Bloggs",
"is_active": true,
"contact": {
"address1": "Bloggs House"
"address2": "1 Bloggs Lane",
"city": "Bloggs Town",
"county": "Bloggs Town",
"zip": "BL0 GG5",
"country": "UK"
}
}
我尝试了以下操作,但它没有工作,我很确定序列化器.ListField的工作原理并不是这样(我认为它的意思是对于相同的事情列表):
class MailChimpListSerializer(serializers.ModelSerializer):
class Meta:
model = Person
contact = serializers.DictField(
address1=serializers.CharField(source='address_line1'),
address2=serializers.CharField(source='address_line2'),
city=serializers.CharField(source='town'),
state=serializers.CharField(source='town', read_only=True),
zip=serializers.CharField(source='post_code'),
country=serializers.SerializerMethodField()
)
permission_reminder = serializers.SerializerMethodField()
campaign_defaults = serializers.DictField(
from_name=serializers.CharField(source='name'),
from_email=serializers.CharField(source='primary_contact_email'),
subject=serializers.CharField(),
language=serializers.CharField()
)
email_type_option = serializers.SerializerMethodField()
fields = ('name', 'contact', 'permission_reminder',
'campaign_defaults', 'email_type_option')
如何创建包含地址等的联系人JSON列表?
答案 0 :(得分:3)
你想要的是DictField
而不是ListField
,你想要的JSON输出中的键contact
是一个对象(Python中的dict),而不是列表:
contact = serializers.DictField(
address1=serializers.CharField(source='address_line1'),
address2=serializers.CharField(source='address_line2'),
...
)
这是另一种更加手动的方式:
class MySerializer(serializers.ModelSerializer):
contact = serializers.SerializerMethodField()
def get_contact(self, obj):
return dict(
address1=obj.address1, # As long as the fields are auto serializable to JSON
some_field=SomeSerializer(obj.some_field).data,
)