wswld
wswld

Reputation: 1238

Overwriting serializer with request data including nulls for absent keys

Let's imagine there is a serializer like this:

class EventSerializer(serializers.ModelSerializer):

    class Meta:
        model = Event
        fields = (
            'title',
            'description'
        )

Where description is nullable. What I want is that the request data completely overwrite the serializer data on PUT request (when updating an existing model instance obviously). If I do:

event_serializer = EventSerializer(event, data=request_data)

It does overwrite everything, but it doesn't nullify description if it is absent from the request. Is there a way to do that without doing manually:

data['description'] = data.get('description', None)

Upvotes: 1

Views: 111

Answers (1)

Sam R.
Sam R.

Reputation: 16450

One option is to define the description field on the serializer and use default like:

class EventSerializer(serializers.ModelSerializer):
    
    # Use proper field type here instead of CharField
    description = serializers.CharField(default=None)

    class Meta:
        model = Event
        fields = (
            'title',
            'description'
        )

See the documentation as well:

default

If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.

May be set to a function or other callable, in which case the value will be evaluated each time it is used.

Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.

Upvotes: 1

Related Questions