这是我的模型:
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/