[Django]-Django rest_framework 3.22 multiple updates creating objects instead of updating

0👍

The problem is that id fields are read_only=True in DRF’s ModelSerializer hence they are dropped in the validation cycle. Making update to work requires more work. I had to do something similar for DRF-bulk and the solution I ended up turned out was to create a serializer mixin which would put the id back. You can see the source code here. Also I have some additional information in the README.

In case the code gets moved or something like that, here is the copy-paste of the serializer mixin:

class BulkSerializerMixin(object):
    def to_internal_value(self, data):
        ret = super(BulkSerializerMixin, self).to_internal_value(data)

        id_attr = getattr(self.Meta, 'update_lookup_field', 'id')
        request_method = getattr(getattr(self.context.get('view'), 'request'), 'method', '')

        # add update_lookup_field field back to validated data
        # since super by default strips out read-only fields
        # hence id will no longer be present in validated_data
        if all((isinstance(self.root, BulkListSerializer),
                id_attr,
                request_method in ('PUT', 'PATCH'))):
            id_field = self.fields[id_attr]
            id_value = id_field.get_value(data)

            ret[id_attr] = id_value

        return ret

0👍

I spoke with tomchristie on IRC. Adding an explicit id field in my serializer and making it not read_only solved the issue.

Leave a comment