gpt4 book ai didi

python - Django 字段的默认值是什么?

转载 作者:行者123 更新时间:2023-11-30 23:18:08 24 4
gpt4 key购买 nike

根据Django Model Documentation、nullblank 选项默认为 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 = FalseIntegerField 的结果为 None,之后在创建或保存时您将收到 ValidationError () 因为值不在 int()

对于 CharField,您将得到“”空字符串,因为 CharField 具有 empty_strings_allowed = True

附注正如 Django 文档所述,避免在 CharFieldTextField 上使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com