当值为空时,Django modelSerializer form.is_valid() 为真
Posted
技术标签:
【中文标题】当值为空时,Django modelSerializer form.is_valid() 为真【英文标题】:Django modelSerializer form.is_valid() is true when values are empty 【发布时间】:2022-01-02 20:40:53 【问题描述】:当我运行form.is_valid()
时,它返回true,除了branchs_count 和employee_count。当我运行 form.save()
时,它会返回关键错误
序列化器.py
class GeneralInformationFormSerializer(serializers.ModelSerializer):
class Meta:
model = Business
fields = ['location', 'date_founded', 'employee_count', 'branches_count', 'business_premises']
def update(self, instance, validated_data):
return update_business_details(instance, validated_data)
这是models.py
class Business(SyncedBusinessModel):
location = models.TextField(blank=True)
employee_count = models.IntegerField(blank=True, null=True)
branches_count = models.IntegerField(blank=True, null=True)
business_premises = models.CharField(max_length=255, blank=True, choices=BUSINESS_PREMISES_CHOICES)
date_founded = models.DateField(blank=True, null=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "businesses"
【问题讨论】:
【参考方案1】:我的模型字段有 blank=True 这意味着验证将通过空白值。由于我不想强制模型字段,但希望这个特定的序列化程序要求它们用于其他应用程序,我将 extra_kwargs 字段添加到序列化程序并解决了问题
class GeneralInformationFormSerializer(serializers.ModelSerializer):
class Meta:
model = Business
fields = ['location', 'date_founded', 'employee_count', 'branches_count', 'business_premises']
# Ensure these values are availed and empty strings
extra_kwargs =
'location': 'required': True, 'allow_blank': False,
'date_founded': 'required': True,
'business_premises': 'required': True, 'allow_blank': False
【讨论】:
以上是关于当值为空时,Django modelSerializer form.is_valid() 为真的主要内容,如果未能解决你的问题,请参考以下文章