我有一个模型,其中数据是通过 API 调用通过前端表单填写的。我有一个更新 api,其中所有字段都设置为 required=False。
我是按照以下方式完成的:
class LeadSerializer(serializers.ModelSerializer):
email= serializers.EmailField(required=False)
phone = serializers.CharField(required=False)
first_name = serializers.CharField(required=False)
last_name = serializers.CharField(required=False)
class Meta:
model = Lead
# fields = '__all__'
# depth = 1
fields = ['id','title','first_name','last_name','address','company_name',
'city','state','country','phone','source','mobile',
'email','gender','date_created','lead_status']
这里我只显示了四个字段作为
required=False
但我需要这个用于所有字段。如何通过在序列化器中编写 init 函数而不是手动编写每个字段来将所有字段设置为 false?
PS 我使用相同的序列化器(上面的序列化器)来创建、列出和更新。
您可以通过覆盖 init 方法在序列化程序中动态地将所有字段设置为 required=False 以进行更新操作。你可以这样做
class LeadSerializer(serializers.ModelSerializer):
email= serializers.EmailField(required=False)
phone = serializers.CharField(required=False)
first_name = serializers.CharField(required=False)
last_name = serializers.CharField(required=False)
class Meta:
model = Lead
fields = ['id','title','first_name','last_name','address','company_name',
'city','state','country','phone','source','mobile',
'email','gender','date_created','lead_status']
def __init__(self, *args, **kwargs):
# Call the parent __init__ method
super(LeadSerializer, self).__init__(*args, **kwargs)
# If this is an update (i.e., partial update), set all fields as not required
if self.context.get('view').action == 'partial_update':
for field in self.fields:
self.fields[field].required = False
要在序列化器中实现此目的,您需要使用
extra_kwargs
Meta 选项。下面有一个用法示例:
class Meta:
model = Lead
# fields = '__all__'
# depth = 1
fields = ['id','title','first_name','last_name','address','company_name',
'city','state','country','phone','source','mobile',
'email','gender','date_created','lead_status']
extra_kwargs = {
'company_name': {'required': False},
'city': {'required': False},
}