模型:
class MyClass(models.Model):
car = models.ForeignKey(Car)
date = models.DateTimeField(auto_now=True, auto_now_add=True)
SQL:
SELECT car FROM cars_myclass WHERE date < NOW() - INTERVAL 1 DAY;
所以,我有类似的东西:
cars = MyClass.objects.all().filter(date < ... )
但如何写NOW() - INTERVAL 1 DAY
?感谢。
答案 0 :(得分:5)
传递datetime.datetime
对象(由datetime.timedelta
对象减去):
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 12, 29, 21, 54, 30, 836000)
>>> now - datetime.timedelta(days=1)
datetime.datetime(2013, 12, 28, 21, 54, 30, 836000)
import datetime
cars = MyClass.objects.filter(date__lt=datetime.datetime.now() - datetime.timedelta(days=1))
更新:Mikko Ohtamaa的评论:
另外为避免时区问题,我建议使用timezone.now()
代替datetime.datetime.now()
(自Django 1.4起可用)
import datetime
from django.utils import timezone
cars = MyClass.objects.filter(date__lt=timezone.now() - datetime.timedelta(days=1))