可更新的嵌套序列化程序
默认情况下,嵌套序列化程序不支持创建和更新。要在不复制 DRF 创建/更新逻辑的情况下支持此操作,在委派给 super
之前从 validated_data
中删除嵌套数据非常重要 :
# an ordinary serializer
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('phone', 'company')
class UserSerializer(serializers.ModelSerializer):
# nest the profile inside the user serializer
profile = UserProfileSerializer()
class Meta:
model = UserModel
fields = ('pk', 'username', 'email', 'first_name', 'last_name')
read_only_fields = ('email', )
def update(self, instance, validated_data):
nested_serializer = self.fields['profile']
nested_instance = instance.profile
# note the data is `pop`ed
nested_data = validated_data.pop('profile')
nested_serializer.update(nested_instance, nested_data)
# this will not throw an exception,
# as `profile` is not part of `validated_data`
return super(UserDetailsSerializer, self).update(instance, validated_data)
在 many=True
的情况下,Django 会抱怨 ListSerializer
不支持 update
。在这种情况下,你必须自己处理列表语义,但仍然可以委托给 nested_serializer.child
。