我有一个像这样的序列化器:
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
发生了什么事?
答案 0 :(得分:8)
来自文档:
注意:当验证应用于ModelSerializer时,两者都是 序列化程序字段及其相应的模型字段必须正确 验证。如果您的模型上有可选字段,请确保 在模型字段上正确设置blank = True,以及设置 序列化器字段上的required = False。