简体   繁体   English

使用django-rest-framework将模型对象序列化为JSON dict

[英]Serialize model objects into a JSON dict using django-rest-framework

So if I have the following model class in Django: 因此,如果我在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)

and my goal is to serialize it into the following JSON: 我的目标是将其序列化为以下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"
    }
}

I tried the following, but it didn't work and I'm pretty sure that's not how the serializers.ListField is meant to work (I think it's meant to be for a list of the same thing): 我尝试了以下操作,但是没有用,我很确定那不是serializers.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')

How do I create the contact JSON list with the address etc in it? 如何创建带有地址等的联系人JSON列表?

What you want is a DictField not a ListField , the key contact in your desired JSON output is an object (dict in Python), not a list: 您想要的是DictField而不是ListField ,所需的JSON输出中的关键contact是一个对象(Python中的dict),而不是列表:

contact = serializers.DictField(
            address1=serializers.CharField(source='address_line1'),
            address2=serializers.CharField(source='address_line2'),
            ...
)

Here's another way that is more manual: 这是另一种更手动的方式:

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,
        )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 django-rest-framework 以 python 关键字序列化 JSON - Serialize JSON with a python keyword using the django-rest-framework 如何使用django-rest-framework序列化ValuesQuerySet? - How to serialize a ValuesQuerySet using django-rest-framework? 在DRF(django-rest-framework)中,如果模型有两个foreignkeyfield,是否可以序列化? - In DRF(django-rest-framework), If model has two foreignkeyfield, is it possible to serialize? 在 Django-rest-framework 中创建具有关系的模型 - Creating Model with Relations in Django-rest-framework django-rest-framework:如何序列化已经包含JSON的字段? - django-rest-framework: How Do I Serialize a Field That Already Contains JSON? django-rest-framework 接受 JSON 数据? - django-rest-framework accept JSON data? 如何将OneToOneField序列化为Django-Rest-Framework中的列表? - How can I serialize the OneToOneField to be list in Django-Rest-Framework? django-rest-framework:如何序列化数据库模型的连接? - django-rest-framework: How to serialize join of database models? 如何在 django-rest-framework 的序列化器中使用时区序列化时间? - how to serialize time with timezone in django-rest-framework's serializer? 如何在Django-rest-framework中序列化具有自定义关系的2个模型? - How to serialize 2 models with custom relationship in django-rest-framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM