gpt4 book ai didi

Django 查询计数始终返回 0

转载 作者:行者123 更新时间:2023-12-04 05:29:35 27 4
gpt4 key购买 nike

这是我的模型:

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()

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

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

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