简体   繁体   中英

How to serialize in Django Rest Framework with custom fields?

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 'user@example.org'.

What should I do?

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  

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