可更新的巢狀序列化程式

預設情況下,巢狀序列化程式不支援建立和更新。要在不復制 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