How to call serializer's create() method from one serializer

Sunny Chaudhari picture Sunny Chaudhari · Jan 19, 2017 · Viewed 16.4k times · Source

I have two serializers, "UserSerializer" and "CustomerSerializer" as bellow

class UserSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        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__'

When I hit user api with POST request, it calls UserSerializer's create method which saves user object.

Now while saving user I want to save customer object as well, using user api. So for from UserSerializer's create method I want to call CustomerSerializer's create() method in order to save customer object as well. How do I do that ?

Answer

Edwin Lunando picture Edwin Lunando · Jan 19, 2017

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__'