根据Django Model Documentation、null
和 blank
选项默认为 False
。那么,如果我没有明确提供 IntegerField
的默认值,那么它的默认值是多少?此外,CharField
和其他内容也会有所帮助。
最佳答案
正如我们在字段方法中看到的
def has_default(self):
"""
Returns a boolean of whether this field has a default value.
"""
return self.default is not NOT_PROVIDED
def get_default(self):
"""
Returns the default value for this field.
"""
if self.has_default():
if callable(self.default):
return self.default()
return force_text(self.default, strings_only=True)
if (not self.empty_strings_allowed or (self.null and
not connection.features.interprets_empty_strings_as_nulls)):
return None
return ""
由于 empty_strings_allowed = False
,IntegerField
的结果为 None
,之后在创建或保存时您将收到 ValidationError ()
因为值不在 int()
对于 CharField,您将得到“”空字符串,因为 CharField
具有 empty_strings_allowed = True
附注正如 Django 文档所述,避免在 CharField
和 TextField
上使用 null=True
Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.
关于python - Django 字段的默认值是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936900/