【问题标题】:Django ImageField null=True doesn't make blank field equal to NULLDjango ImageField null=True 不会使空白字段等于 NULL
【发布时间】:2021-01-20 12:16:29
【问题描述】:

我有一个带有这个字段的模型:

carousel_image = models.ImageField(upload_to='news/%Y/%m/%d, null=True, blank=True)

我想知道为什么 exclude(carousel_image__isnull=True) 和其他检查字段是否为空的查询不起作用。 我检查了我的 sqlite3 数据库并收到了这个:

sqlite> select carousel_image from asgeos_site_news;
news/2020/12/23/index.jpeg
news/2020/12/23/gradient-1.jpeg



( 3 blank lines )

我还尝试添加 WHERE carousel_image = NULL,但它什么也没返回。 为什么我的图像不为空?它们只是一个空白行。我现在必须使用 carousel_image__exact='' 来排除它们。

【问题讨论】:

    标签: sql django database sqlite django-models


    【解决方案1】:

    数据库中的文件字段不能设置为空,here's the reference from django documentation

    blank = True
    

    够了。

    空白存储为''

    【讨论】:

    • 但它已有 12 年历史,现代文档建议将 null=True 设置为文件字段。
    • 上次修改时间为 4 年前。你介意分享它建议的链接吗?
    • ImageField 或 FileField 是一个基于字符串的字段,用于存储文件的路径。 Django 建议不要对任何基于字符串的字段使用 null。查看最新文档:docs.djangoproject.com/en/3.1/ref/models/fields/#null
    • 哦,谢谢,我一定是在什么地方看错了。
    猜你喜欢
    • 2017-03-07
    • 2012-03-22
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 2011-03-13
    • 2015-11-09
    相关资源
    最近更新 更多