我有以下序列化程序:
class ReqSerializer(serializers.ModelSerializer):
class Meta:
model = Earth
fields = ('area', )
和这个模型:
class Earth(models.Model):
area = models.IntegerField(default=0)
根据 django-rest-framework Serializer fields “必需”选项是
默认情况下设置为 True 这意味着如果我尝试验证输入中没有“区域”字段的序列化程序,
我应该得到 This field is required
错误。但是 is_valid()
被传递并且模型被创建为默认 area=0
。然而,使用这个:
extra_kwargs = {
area': {'required': True},
}
会解决问题,但为什么呢?什么可以改变这种行为?为什么默认“required=True” 没有效果?
更新:
我刚刚注意到,如果我从模型中删除 default=0
,它将按预期工作。现在的问题是为什么在模型字段上设置默认值会取消序列化程序上的 required=True
。
最佳答案
我认为您的问题是该字段是由 Django REST 框架自动生成的,而文档是从您在序列化程序上手动创建该字段的角度来看的。
According to django-rest-framework Serializer fields the "required" option is set to True by default
这对于您在序列化程序上自行指定的字段是正确的。在自动生成字段的情况下,Django REST 框架会尝试确定与模型字段最匹配的序列化程序字段选项,类似于 Django forms does it for form fields 的方式。 .对于序列化程序字段,目前大部分内容都没有记录,因此我无法向您指出任何内容。
But is_valid() is passed and the model gets created with default area=0.
这是因为 Django REST framework 确定该字段具有默认值,此时知道输入不是严格要求因为模型字段会自动给出默认值 如果用户没有传入任何内容。当然,如果您在创建时将某些内容传入序列化程序,将使用该值而不是默认值,如果您手动创建模型,这是您所期望的。
Would solve the issue but why? What could change this behavior? Why the default "required=True" has no effect?
这将解决您的问题,因为它手动覆盖了在自动生成的序列化程序字段上设置的 required=False
。在 Django REST framework 3.0 中,您可以通过 calling repr(ReqSerializer())
and looking at the the automatically generated field 确认.
I just noticed that if I remove the default=0 from the model, it will work as expected.
这是因为 Django REST framework 不再确定默认值并将 required=True
添加到序列化程序,就像您期望的那样。
关于python - django-rest-framework 对字段 "required"选项的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27812252/