gpt4 book ai didi

python - serializer.is_valid() 虽然 `required=False` 失败 - Django REST Framework

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:55 24 4
gpt4 key购买 nike

我有一个像这样的序列化器:

class DataSetColumnSerializer(serializers.ModelSerializer):
custom_target = serializers.PrimaryKeyRelatedField(required=False)

class Meta:
model = dataset_models.DataSetColumn

然而:

ipdb> columns[0]
{u'display_name': u'guid', u'name': u'guid', u'data_type': u'STRING', u'custom_target': None, u'ignore': False, u'is_identifier': False, u'order': 1}
ipdb> serializer.is_valid()
False
ipdb> serializer.errors
[{'custom_target': [u'This field cannot be blank.']}, {'custom_target': [u'This field cannot be blank.']}, {'custom_target': [u'This field cannot be blank.']}, {'custom_target': [u'This field cannot be blank.']}, {'custom_target': [u'This field cannot be blank.']}, {'custom_target': [u'This field cannot be blank.']}, {'custom_target': [u'This field cannot be blank.']}, {'custom_target': [u'This field cannot be blank.']}]
ipdb> serializer.fields['custom_target'].required
False

这是怎么回事?

最佳答案

来自文档:

Note: When validation is applied to a ModelSerializer, both the serializer fields, and their corresponding model fields must correctly validate. If you have optional fields on your model, make sure to correctly set blank=True on the model field, as well as setting required=False on the serializer field.

link to docs

关于python - serializer.is_valid() 虽然 `required=False` 失败 - Django REST Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25294993/

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