Skip to content

Unable to override required argument on a read_only field in extra_kwargs #3091

@ashleyredzko

Description

@ashleyredzko

Fields that are set to "read_only": True are not passed to update() on a serializer. A work around to this was to add "read_only": False to extra_kwargs for that field. This would pass the value to update and allow us to use it.

One problem then is with required fields. In create(), these fields must be supplied by default. However, for something like an auto-generated UUID or primary key, we cannot provide it. To work around this, we set "required": False in the extra_kwargs for that field as well.

In 3.1.2, this behavior allowed creation without that field provided and update was passed it's value. In 3.1.3, this isn't possible because the field is now required and validation fails. This behavior seems to be changed due to #2975.

In #2975, if read_only is set to True in the model or serializer fields, it drops the required value in extra_kwargs and defaults to the model or serializer field values. However, we've set the value for read_only to False in extra_kwargs. The problem is that the serializer is still assuming the value is True since it is pulling from the model or serializer fields and not extra_kwargs, overriding the behavior we want.

Here is an example usage:

serializers.py

class AlbumSerializer(serializers.ModelSerializer):

    class Meta:
        model = Album

        fields = (
            'id', 'artist', 'producer',
            'year', 'price'
        )

        extra_kwargs = {
            "id": {
                "required": False,
                "read_only": False
            }
        }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions