[Fixed]-How to call serializer's create() method from one serializer

17đź‘Ť

âś…

You can call the CustomerSerializer from the create method inside the UserSerializer. E.G.

class UserSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        customer_serializer = CustomerSerializer(validated_data.get('customer'))
        customer_serializer.save()
        return User.objects.create(**validated_data)

    class Meta:
        model = User
        fields = '__all__'
👤Edwin Lunando

6đź‘Ť

@Edwin…The solution is perfect just the thing I have made some changes in my data dictionary and send it to “CustomerSerializer” as bellow, and it started working. Thanks for your help and bellow code works for me now.

class UserSerializer(serializers.ModelSerializer):
    def get_serializer_context(self):
        return self.context['request'].data

    def create(self, validated_data):

        request_data = dict(self.get_serializer_context())

        cust_req_data = {'first_name':request_data['first_name'][0], 
                         'last_name':request_data['last_name'][0],
                         'email':request_data['email'][0]
                        }

        customer_serializer = CustomerSerializer(data=cust_req_data)
        if customer_serializer.is_valid():
            customer_serializer.save()

        return User.objects.create(**validated_data)

class Meta:
    model = User
    fields = '__all__'


class CustomerSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        return Customer.objects.create(**validated_data)

    class Meta:
        model = Customer
        fields = '__all__'

Also “if customer_serializer.is_valid():” this condition is required before saving object using CustomerSerializer

I have added “data” which is dict which i need to validate for my customer data fields,

since as I have explained previously that this is POST request I’m sending some data which is required to store user using UserSerializer and some data is required to store customer using CustomerSerializer using one user api itself.

so “get_serializer_context” method gives the entire post request data from that I get only those fields which are required to save customer and I have passed that dict as parameter to CustomerSerializer

“customer_serializer = CustomerSerializer(data=cust_req_data)”

This works for me.

Leave a comment