【问题标题】:serializer.is_valid() failing though `required=False` - Django REST Frameworkserializer.is_valid() 虽然 `required=False` 失败 - Django REST Framework
【发布时间】:2014-08-13 19:55:11
【问题描述】:

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

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

发生了什么事?

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    来自文档:

    注意:当对 ModelSerializer 应用验证时, 序列化器字段及其对应的模型字段必须正确 证实。如果您的模型上有可选字段,请确保 在模型字段上正确设置空白=真,以及设置 序列化器字段上的 required=False。

    link to docs

    【讨论】:

    • 明白了。这样可行。我有null=True,但缺少blank=True。感谢您为我指明正确的方向。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2013-11-28
    • 2021-02-28
    • 1970-01-01
    相关资源
    最近更新 更多