我试图过滤一个DateTimeField与日期比较。我的意思是:
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
我得到一个空的查询集列表作为答案,因为(我认为)我没有考虑时间,但我想要“任何时间”。
Django中有简单的方法来做这个吗?
我在datetime中设置了时间,不是00:00。
我试图过滤一个DateTimeField与日期比较。我的意思是:
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
我得到一个空的查询集列表作为答案,因为(我认为)我没有考虑时间,但我想要“任何时间”。
Django中有简单的方法来做这个吗?
我在datetime中设置了时间,不是00:00。
当前回答
这里有一篇很棒的博客文章介绍了这一点:比较Django ORM中的日期和日期时间
Django>1.7,<1.9的最佳解决方案是注册一个转换:
from django.db import models
class MySQLDatetimeDate(models.Transform):
"""
This implements a custom SQL lookup when using `__date` with datetimes.
To enable filtering on datetimes that fall on a given date, import
this transform and register it with the DateTimeField.
"""
lookup_name = 'date'
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return 'DATE({})'.format(lhs), params
@property
def output_field(self):
return models.DateField()
然后你可以像这样在你的滤镜中使用它:
Foo.objects.filter(created_on__date=date)
EDIT
这个解决方案绝对依赖于后端。摘自文章:
当然,此实现依赖于具有DATE()函数的特定SQL风格。MySQL。SQLite也是如此。另一方面,我个人没有使用过PostgreSQL,但一些谷歌搜索让我相信它没有DATE()函数。因此,如此简单的实现似乎必然是后端依赖的。
其他回答
Model.objects.filter(datetime__year=2011, datetime__month=2, datetime__day=30)
嗯. .我的解决方案是有效的:
Mymodel.objects.filter(date_time_field__startswith=datetime.datetime(1986, 7, 28))
这里有一篇很棒的博客文章介绍了这一点:比较Django ORM中的日期和日期时间
Django>1.7,<1.9的最佳解决方案是注册一个转换:
from django.db import models
class MySQLDatetimeDate(models.Transform):
"""
This implements a custom SQL lookup when using `__date` with datetimes.
To enable filtering on datetimes that fall on a given date, import
this transform and register it with the DateTimeField.
"""
lookup_name = 'date'
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return 'DATE({})'.format(lhs), params
@property
def output_field(self):
return models.DateField()
然后你可以像这样在你的滤镜中使用它:
Foo.objects.filter(created_on__date=date)
EDIT
这个解决方案绝对依赖于后端。摘自文章:
当然,此实现依赖于具有DATE()函数的特定SQL风格。MySQL。SQLite也是如此。另一方面,我个人没有使用过PostgreSQL,但一些谷歌搜索让我相信它没有DATE()函数。因此,如此简单的实现似乎必然是后端依赖的。
MyObject.objects.filter(datetime_attr__date=datetime.date(2009,8,22))
Mymodel.objects.filter(date_time_field__contains=datetime.date(1986, 7, 28))
以上就是我所使用的。它不仅有效,而且有一些内在的逻辑支持。