如何使用自定义字段在Django Rest Framework中序列化?

时间:2018-02-19 15:28:49

标签: python django django-rest-framework

假设我的模型是:

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

我想要一个接收多个字段的序列化程序,然后将它们组合起来创建一个电子邮件。例如:

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

它会将{“first”:“user”,“second”:“example”,“third”:“org”}转换为新的Contact对象,电子邮件为“user@example.org”。

我该怎么办?

1 个答案:

答案 0 :(得分:2)

您可以覆盖序列化程序的create方法:

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