我的模型中有一个名为 created_at
的 DateTimeField
。我想查询今天创建的对象。来自 this question我使用了以下查询集,
In [70]: today = datetime.datetime.today().date()
In [72]: Business.objects.filter(created_at__date=today)
Out[72]: <QuerySet []>
它返回零结果。我已确保数据库中有一个今天创建的条目。我知道我也可以使用
Business.objects.filter(created_at__contains=today)
但它产生的结果带有警告:
django/db/backends/mysql/base.py:71: Warning: (1292, "Incorrect datetime value: '%2017-12-21%' for column 'created_at' at row 1")
我正在使用 MySQL 数据库。我的模型是
class Business(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
url = models.CharField(max_length=255, blank=True, null=True)
created_at = models.DateTimeField()
category = models.CharField(max_length=120)
class Meta:
managed = False
db_table = 'Business'
unique_together = (('name', 'url'),)
最佳答案
from django.utils import timezone
Business.objects.filter(created_at__gte=timezone.now())
我想这对你来说会更好。
并更改您的模型
created_at = models.DateTimeField(auto_now=True)
然后makemigrations,迁移然后添加一些数据并重试
关于python - Django DateTimeField 日期过滤器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47918295/