我有两个序列化程序,"UserSerializer"和"CustomerSerializer"如下所示
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__'
当我用POST请求命中用户api时,它调用UserSerializer的create方法来保存用户对象.
现在,在保存用户的同时,我也希望使用用户api保存客户对象.因此,对于UserSerializer的create方法,我想调用CustomerSerializer的create()方法以便保存客户对象.我怎么做 ?
你可以CustomerSerializer
从create
里面的方法中调用UserSerializer
.例如
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__'