django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

Serializer.run_validators does not add defaults from read_only fields to data.

Open pyrocat opened this issue 2 years ago • 3 comments

It seems there's a typo in Serializer.run_validators method which is supposed to update initial data with default values from read-only fields. Instead, the value remains unchanged.

 def run_validators(self, value):
      """
      Add read_only fields with defaults to value before running validators.
      """
      if isinstance(value, dict):
          to_validate = self._read_only_defaults()
          to_validate.update(value)
      else:
          to_validate = value
      super().run_validators(to_validate)

Looks like it should be value.update(to_validate) instead of to_validate.update(value)

pyrocat avatar May 04 '23 13:05 pyrocat

can you send a PR with unit tests?

auvipy avatar May 06 '23 05:05 auvipy

I think this code is correct.

  • If there is a readonly field and the field is not in value, use the default value
  • If there is a readonly field and the field is in value, use the value in value
  • Cannot add the readonly field to value, because of the validated_data corresponding to value

yabea avatar May 06 '23 10:05 yabea

in that case we can close this issue or move this to discussion

auvipy avatar May 07 '23 05:05 auvipy