![](/img/trans.png)
[英]How to compare DateTimeField with Date in Django filter funtion?
[英]Django DateTimeField date filter not working
我的模型中有一個名為created_at
的DateTimeField
。 我想查詢今天創建的對象。 根據這個問題,我使用了以下查詢集,
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)
然后進行遷移,遷移,然后添加一些數據,然后重試
使用時區庫
today = timezone.datetime.today().date()
其他
today = timezone.now().date()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.