用请求数据覆盖序列化程序,包括不存在键的空值

2024-04-27 03:25:44 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有这样一个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)

Tags: 数据eventfieldsdatamodelputtitledescription
1条回答
网友
1楼 · 发布于 2024-04-27 03:25:44

一个选项是在序列化程序上定义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.

相关问题 更多 >