Skip to main content
 首页 » 编程设计

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

2025年05月04日13qq78292959

让我们假设有一个像这样的 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.