Django 查询 Count 始终返回 0

标签 django django-queryset

这是我的模型:

class People(models.Model):
    name = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)

在views.py中

-当我尝试此方法来计算空姓氏字段时:

People.objects.filter(lastname__isnull=True).count()

尽管有一些空的姓氏字段,但它始终返回 0 事件。

为什么我得到 0,我的代码有什么问题吗?或者有其他方法来计算表中的空字段吗?

最佳答案

您的CharField很可能存储空字符串,而不是NULL

Django docs on null field value

Field.null
If True, Django will store empty values as NULL in the database. Default is False.

Note that empty string values will always get stored as empty strings, not as NULL. Only use null=True for non-string fields such as integers, booleans and dates. For both types of fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).

Avoid using null on string-based fields such as CharField and TextField unless you have an excellent reason. 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;” Django convention is to use the empty string, not NULL.

尝试将您的查询更改为:

People.objects.filter(lastname="").count()

空与 NULL 不同。您需要将字段设置为 null=True,正如文档所建议的那样,不建议将其用于 CharField。

关于Django 查询 Count 始终返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12790810/

相关文章:

python - 我应该迭代 Django 查询集还是变量?

python - 如何在管理更新方法中从 Django 查询集中提取 id?

Django: select_for_update() 关于外键关系

python - 当我想在单元测试中使用反向函数时,会发生 django urls.exceptions.NoReverseMatch 错误?

python - 如何使通用 ListView 只显示用户的列表?

python - Django:从 ID 列表中获取一组对象(并按时间戳排序)

python - Django ORM 按两个相关模型的 Max 列值过滤

python - 无法在 linux 上安装 python 设置工具

python - NoseTests 的基本设置

python - 从模板集命名变量调用 Django 方法。这怎么可能?