[Fixed]-Django-rest-framework PUT manytomany through model

1đź‘Ť

Django rest framework documentation states that it is up to developer to implement creates and updates for nested representations.

👤Ivan

0đź‘Ť

Although @Ivan was correct about writing my own create & update fn, the specific issue I was seeing was that the nested serialization did not have an instance attribute associated with it.

The new code looks like this:

serializers.py

class ModelBSerializer(ModelSerializer):

    ....

    def update(self, model_instance, validated_data):
        model_c_serializer = self.fields["other_models"]

        model_c_data = validated_data.pop(model_c_serializer.source, [])

        for key, value in validated_data.iteritems():
            setattr(model_instance, key, value)
        model_instance.save()

        model_c_serializer.update(model_instance.link_to_model_b.all(),
model_c_data)

        return model_instance

class ModelCSerializer(ModelSerializer):

    ...

    def to_internal_value(self, data):

        # this is as good a place as any to set the instance
        try:
            model_class = self.Meta.model
            self.instance = model_class.objects.get(pk=data.get("id"))
        except ObjectDoesNotExist:
            pass

        return super(ModelCSerializer, self).to_internal_value(data)

Basically, I call update for the nested serializers explicitly and I also force each nested serializer to check the data that is passed to them for an instance.

👤trubliphone

Leave a comment