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

标签 python django-models

根据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/

相关文章:

python - 将 MailChimp 与 SendGrid 结合使用

python - 添加对的缺失值

python - 使用一对一和外键字段创建新模型实例

python - Django 根据 ForeignKey 集中的属性过滤对象

Django 和 get_absolute_url

python - openshift-django : syncdb, 部署脚本未运行

python - 在 Pandas 中组合 DataFrame

Python return 语句不会中断 for 循环

python - 使用多个 setup.py 脚本的多个项目?

python - Django 空字段回退