Skip to content

The Serializer data accessor returns cached and stale _data after .update() #2532

Closed
@dennisschaaf

Description

@dennisschaaf

Hey,

I am having a problem with the way _data is cached. We are using the RetrieveUpdateView to update a model with a nested list. The result of the operation is that the database is updated, but the old object is being returned.

The UpdateModelMixin performs an update on the following Serializer:

class MixDesignCreateSerializer(ModelSerializer):
  expiration_date = DateField(format=DATE_FORMAT, input_formats=(DATE_FORMAT,), required=False, )
components = MixComponentSerializer(many=True, required=False)

  def update(self, instance, validated_data):
    # Update nested list
    extracted_components = validated_data.pop('components')
    instance.components = self['components'].update(instance.components, extracted_components)

    instance = super(MixDesignCreateSerializer, self).update(instance, validated_data)

    # The instance is now properly updated in the DB
    # but self._data still contains a cache of the
    # initial _data created during is_valid()

    # The only 'hack' is to delete _data, whilch will
    # force a fetch from the database
    delattr(self, '_data')
    self.is_valid()

    return instance

and then renders the result of serializer.data

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions