简体   繁体   中英

How we can deserialize the nested json object into python model object at once?

When we serialize python model object to nested json data we can serialize it in django as foe example.

DataSerializer(data_list, many=True)

and output will like that.

[
    {"name":"user_1", "id":1}, 
    {"name":"user_2", "id":2}, 
    {"name":"user_3", "id":3},
    ... ...
]

Now I want to deserialize the list of json object to python model object at once.

As for example:

# the serializer class
class UserSerilizer(serializers.Serializer):
    id = serializers.IntegerField(required=True)
    name = serializers.CharField(required=True)


# Request model class.
class UserRequestModel:
    id = None
    name = None

    def __init__(self, dictionary):
        self.__dict__.update(dictionary)

And what I do.

# serialize the request data for param validation
user_serializer = UserSerilizer(data=request.data)

# update the user request model with validate data
user_data = UserRequestModel(user_serializer.validated_data)

That's why I can access the value user_data.id and user_data.name for the request body {"name":"user_1", "id":1}

But how can I do it for list of data at once like we serialize at once with passing parameter DataSerializer(data_list, many=True) .

Just append deserialize method in your Serializer class

class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=True)
    name = serializers.CharField(required=True)

    @classmethod
    def deserialize(cls, data, many=False):
        if many is False:
            return UserRequestModel(data)
        else:
            obj_list = []
            for d in data:
                obj_list.append(UserRequestModel(d))
            return obj_list

But I can not understand why you want to deserialize. I don't think this is recommended in django.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM