如何使用嵌套对象序列化Django模型(Django REST Framework) [英] How to serialize Django models with nested objects (Django REST Framework)

查看:279
本文介绍了如何使用嵌套对象序列化Django模型(Django REST Framework)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个序列化程序,一个是嵌套的,那么如何设置restore_object方法?例如,如果我定义了以下序列化器,那么我如何为我的嵌套序列化程序定义还原对象字段?从文档中可以看出如何处理这种情况并不明显。

If I have two serializers, where one is nested, how do I setup the restore_object method? For example, if I have the following serializers defined, how do I define the restore object field for my nested serializer? It is not obvious from the documentation how to handle such a case.

class UserSerializer(serializers.Serializer):
    first_name = serializers.CharField(required=True, max_length=30)
    last_name = serializers.CharField(required=True, max_length=30)
    username = serializers.CharField(required=True, max_length=30)
    email = serializers.EmailField(required=True)
    password = serializers.CharField(required=True)

    def restore_object(self, attrs, instance=None):
        if instance:
            instance.first_name = attrs.get('first_name', instance.first_name)
            instance.last_name = attrs.get('last_name', instance.last_name)
            instance.email = attrs.get('email', instance.email)
            instance.password = attrs.get('password', instance.password)

class UserProfileSerializer(serializers.Serializer):
    user = UserSerializer()
    bio = serializers.CharField()
    def restore_object(self, attrs, instance=None):
        if instance:
            instance.bio = attrs.get('bio', instance.bio)
            instance.user = ?????


推荐答案

重要sidenote: em>看起来你正在使用旧的User / Profile方法。由于Django 1.5没有分离默认的用户和您的自定义配置文件模型。您必须创建自己的用户模型,而不是默认用户模型: Django文档的自定义用户个人资料

Important sidenote: It looks like you are using the old User/Profile methodology. Since Django 1.5 there is no seperation of the default User and your custom Profile models. You have to create your own user model and use that instead of the default one: Custom User Profile @ Django Docs

I想给你一个不同的方法来序列化和恢复模型。通过使用以下代码段,所有模型对象可以序列化

I want to present you a different approach to serialize and restore models. All model objects can be serialized by using the following snippet:

from django.core import serializers
serialized_data = serializers.serialize("json", myInstance)

序列化多个对象

serialized_data = serializers.serialize("json", User.objects.all())

然后将外键和m2m关系存储在ids的数组中。

Foreign keys and m2m relations are then stored in an array of ids.

如果您只希望序列化 子集

If you want only a subset of fields to be serialized:

serialized_data = serializers.serialize("json", myUserInstance, fields=('first_name ','last_name ','email ','password '))

要保存用户个人资料,您只需写入:

To save the user profile you would just write:

serialized_data = serializers.serialize("json", myUserProfileInstance)

用户ID保存在seriali zed数据,如下所示:

The user id is saved in the serialized data and looks like this:

{
    "pk": 1,
    "model": "profile.UserProfile",
    "fields": {
        "bio": "self-taught couch potato",
        "user": 1
    }
}

如果您希望序列化中的相关用户字段也需要修改您的用户模型:

If you want related user fields in the serialization too, you need to modify your User model:

class UserManager(models.Manager):
    def get_by_natural_key(self, first_name, last_name):
        return self.get(first_name=first_name, last_name=last_name)

class User(models.Model):
    objects = UserManager()

    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    ...

    def natural_key(self):
        return (self.first_name, self.last_name)

    class Meta:
        unique_together = (('first_name', 'last_name'),)

当串行使用自然键调整您需要添加 use_natural_keys 参数:

When serializing with natural keys you need to add the use_natural_keys argument:

serialized_data = serializers.serialize("json", myUserProfileInstance, use_natural_keys=True)

哪些导致以下输出:

{
    "pk": 2,
    "model": "profile.UserProfile",
    "fields": {
        "bio": "time-traveling smartass",
        "user": ["Dr.", "Who"]
    }
}



反序列化



反序列化和保存同样简单:

for deserialized_object in serializers.deserialize("json", serialized_data):
    deserialized_object.save()

更多信息可以在Django文档中找到:一个href =https://docs.djangoproject.com/en/dev/topics/serialization/>序列化Django对象

More information can be found in the Django docs: Serializing Django objects

这篇关于如何使用嵌套对象序列化Django模型(Django REST Framework)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆