django rest framework 3.1 - ModelSerializer - 嵌套表示的多重更新

时间:2015-06-25 21:14:09

标签: python serialization django-rest-framework

在我的ModelSerializer中,我有一个带many=True的嵌套ModelSerialier。问题是如何在update方法中更新所有嵌套实例?

class ProfileSerializer(serializers.ModelSerializer):
    things = serializers.ThingsSerializer(many=True)


    def update(self, instance, validated_data):
        things_data = validated_data.pop('things')
        instance = super(ProfileSerializer, self).update(instance, validated_data)

        # here i can't access to ids of things as this is read-only field and it isn't passed to validated_data

        return instance

1 个答案:

答案 0 :(得分:0)

正如你所说,因为ID是只读的,所以它不会通过validated_data。我设法完成它的唯一方法(几个小时......之后)是将id设为integerField:

class ProfileSerializer(serializers.ModelSerializer):
    things = serializers.ThingsSerializer(many=True)
    id = serializers.IntegerField() # Do this for avoid read-only id!


    def update(self, instance, validated_data):
        things_data = validated_data.pop('things')
        instance = super(ProfileSerializer, self).update(instance, validated_data)

        things_id = things_data['id'] # Now this is possible!

        return instance