gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:55:40 25 4
gpt4 key购买 nike

让我们假设有一个像这样的 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 thefield if no input value is supplied. If not set the default behavioris to not populate the attribute at all.

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

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

关于python - 使用请求数据覆盖序列化程序,包括缺少键的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27947100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com