serializer.is_valid()失败但是'required = False` - Django REST Framework

han*_*sen 3 python django django-rest-framework

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

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

    class Meta:
        model = dataset_models.DataSetColumn
Run Code Online (Sandbox Code Playgroud)

然而:

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
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

crh*_*des 9

来自文档:

注意:将验证应用于ModelSerializer时,序列化程序字段及其对应的模型字段都必须正确验证.如果模型上有可选字段,请确保在模型字段上正确设置blank = True,并在serializer字段上设置required = False.

链接到docs