假设我的模型是:
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”。
我该怎么办?
答案 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