使用请求数据覆盖序列化程序,包括缺少键的空值

Overwriting serializer with request data including nulls for absent keys

让我们想象有这样一个 serializer

class EventSerializer(serializers.ModelSerializer):

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

其中 description 可以为空。我想要的是请求数据完全覆盖 PUT 请求上的序列化程序数据(显然更新现有模型实例时)。如果我这样做:

event_serializer = EventSerializer(event, data=request_data)

它确实会覆盖所有内容,但如果请求中没有它,它不会使 description 无效。有没有不用手动操作的方法:

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

一种选择是在序列化器上定义 description 字段并使用 default ,例如:

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

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

另见documentation

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.