2015-09-09 35 views
1

在我的基於Django Rest Framework的序列化器中serializers.ModelSerializer 我聲明的字段只會在導入一些數據(反序列化)時被考慮,而哪些不是反映任何模型領域。django rest框架組合write_only = True和required = False不起作用

new_number = serializers.CharField(
    write_only=True, required=False, 
    allow_null=True, default='' 
) 

Django Rest Framework documentation

write_only 

Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

Defaults to False

required 

Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization.

Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.

Defaults to True.

我ancounter的問題是,當該字段爲空,我得到錯誤: {'new_number': ['This field can not be blank']}

我運行:

djangorestframework==3.2.3 
Django==1.8.4 

回答

1

您需要傳中new_number串行場allow_blank=True說法。其默認值爲False

new_number = serializers.CharField(
    write_only=True, required=False, allow_blank=True, # allow empty string as a valid value 
    default='' 
) 

allow_blank參數文檔:

allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False .

此外,你應該使用allow_blank代替allow_null這裏,而不是兩個,因爲,因爲這將意味着將有2種類型的空值的可能。

The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank. It is valid to set both allow_blank=True and allow_null=True , but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.