0

Let's say my model is:

class Contact(models.Model):
    email = models.CharField(max_length=50)

I want to have a serializer that receives multiple fields and then combine them to create an email. For example:

class ContactSerializer(serializers.Serializer):
    first = serializers.CharField()
    second = serializers.CharField()
    third = serializers.CharField()

It would convert {"first": "user", "second": "example", "third": "org"} to a new Contact object with the email '[email protected]'.

What should I do?

1 Answer 1

2

You can override serializer's create method:

class ContactSerializer(serializers.Serializer):
    first = serializers.CharField()
    second = serializers.CharField()
    third = serializers.CharField()

    def create(self, validated_data):
        email = '{0}@{1}.{2}'.format(validated_data['first'], validated_data['second'], validated_data['third'])
        instance = Contact.objects.create(email=email)
        return instance  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.