django rest framework deserialize object based on custom class

Question:

I would like to deserialize this json:

json1 = {
    "age" : "22",
    "name" : "Bob",
    "lastname" : "Andrew",
    "contactList" : [
    { "friend" : "Alice"},
    {  "friend" : "John"}
]}

I have created the following classes (I dont want to create any models since I am no interested in saving them in the database):

class Friend(object):
    def __init__(self, friend):
        self.friend = friend

class Person(object):
    def __init__(self, age , name , lastname, contactList):
        self.age=age
        self.name = name
        self.lastname = lastname
        self.contactList= []   #possible error here 

and the following serializers:

class FriendSeriliazer(serializers.Serializer):
    friend = serializers.CharField()

    def create(self, validated_data):
        return Friend(**validated_data)

class PersonSerializer(serializers.Serializer):
    age = serializers.CharField()
    name = serializers.CharField()
    lastname = serializers.CharField()
    contactList = FriendSerializer(many=True)

    def create(self, validated_data):
         print validated_data
         simple = Person(**validated_data)
         contactList = self.validated_data.pop('contactList')
         for friend in contactList:
             serializer = FriendSerializert(data=friend)
             if serializer.is_valid(raise_exception=True):
                person.contactList.append(serializer.save())
         return person

The POST method from the view:

    parsedData = PersonSerializer(data=request.data)
    person = parsedData.save()
    print person.contactList[0].friend #<-- nested object should be present  
    return Response(request.data, status=status.HTTP_200_OK)

I used the drf documentation for this

The problem is that while this works I need to deserialize a much more complex json and iterating the inner objects in the create function isn’t gonna cut it. Is there a more automated way?

Asked By: No_Fun

||

Answers:

In your case, you don’t want to save in database but in an object and Django-Rest-Framework doesn’t support writable nested serializers by default, then there is no other better solution than what you are doing. You have to implement this process by yourself.

By default nested serializers are read-only. If you want to support
write-operations to a nested serializer field you’ll need to create
create() and/or update() methods in order to explicitly specify how
the child relationships should be saved.

Read Django-Rest-Framework documentation for more information : Writable nested relationships

Answered By: Louis Barranqueiro

I am trying to do something similar – "want to save the data from the json to an object type of Person class, without saving it to the database".
Is there a better method that anyone found ?

Answered By: stm