【问题标题】:filter none on django field在 django 字段上过滤无
【发布时间】:2013-08-14 12:33:48
【问题描述】:

我有一个模型 Person,它有时在 birth_date 字段中没有任何内容。这是一个例子:

(Pdb) dude = Person.objects.get(pk=20)
(Pdb) dude
<Person: Bob Mandene>
(Pdb) dude.birth_date
(Pdb) dude.birth_date == None
True

如何过滤这些具有birth_date == None 的记录?

我已经尝试了以下方法,但没有成功:

1:“birth_date__isnull”不起作用。

 Person.objects.filter(birth_date__isnull = True) 
 # does not return the required 
 # object.    Returns a record that have birth_date set to 
 # NULL when the table was observed in MySQL.

以下不返回id为20的记录。

Person.objects.filter(birth_date = "")

如何过滤为 None 的字段?看起来 NULL 和 None 是不同的。当我使用 sequel pro(mysql 图形客户端)查看数据时,我看到“0000-00-00 00:00:00”,以下也不起作用

(Pdb) ab=Patient.objects.filter(birth_date = "0000-00-00 00:00:00")
 ValidationError: [u"'0000-00-00 00:00:00' value has the correct format 
 (YYYY-MM-DD     HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time."]

型号

class Person(models.Model):
    person_no = models.IntegerField(primary_key=True)
    locationid = models.IntegerField(null=True, db_column='LocationID', blank=True) 
    address =  models.ForeignKey('Address', db_column = 'address_no')
    birth_date = models.DateTimeField(null=True, blank=True)
    class Meta:
       managed = False
       db_table = 'person'

【问题讨论】:

  • is_null 仅在您在模型中设置 null=True 时才有效;那么模型是什么样的呢?
  • 用模型更新了问题。这是一个从 MsSQL 转移到 MySQL 的遗留表。
  • 据说is_null 必须工作`。如果出生日期的值为空,则必须检查数据库。

标签: django django-models


【解决方案1】:

mysql 中的 NULL 在 python 中变成 None,所以使用birth_date__isnull=True 应该返回那些有birth_date 为 None 的。

【讨论】:

  • 我也是这么想的。这张照片i.imgur.com/vYM5Qyg.png 是来自 sequel pro 的截图。当我执行birth_date__isnull=True 时,第一行/记录被返回。 id=20 的记录在图片的最后一行,它为 dude.birth_date == None 返回 True,并且图片中有 0000-00-00 00:00:00。我需要过滤掉其中包含 0000-00-00 00:00:00 的行(但它们是 None ,如上所示)
  • 如何使用 filter(birth_date__isnull=False) 或 all().exclude(birth_date__isnull=True)
  • filter(birth_date__isnull=False) 会给我所有我不想要的东西。
  • 尝试 Person.objects.all().exclude(birth_date__isnull=True) 调用。
  • Person.objects.all().exclude(birth_date__isnull=True) 返回所有内容。
【解决方案2】:

嗯,我不确定为什么在这种情况下0000-00-00 00:00:00 被转换为None,但您可以尝试使用exact

Person.objects.filter(birth_date__exact=None)

【讨论】:

    【解决方案3】:

    在这里,一些列表理解可能会派上用场:

    persons = [person for person in Person.objects.all() if not person.birth_date]
    

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 2021-06-19
      • 2020-07-29
      • 2021-06-07
      • 2014-08-24
      • 2013-08-06
      • 2021-10-29
      • 2015-02-22
      • 2014-09-04
      相关资源
      最近更新 更多