问题
According to this document that was added on v1.9 we can able to query a DateTimeField
by date without time.
Examples are:
Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
But it is not working for me:
class MilkStorage(models.Model):
....
created_at = models.DateTimeField(null=False)
Usage
from datetime import date
MilkStorage.objects.filter(created_at__date=date.today())
It returns an empty queryset <QuerySet []>
.
Does this query only works on PostgreSQL
? im using MySQL
.
回答1:
Depending on your specific requirements, this may or may not be an ideal solution. I found that __date works if you set USE_TZ = False in settings.py
I had this same problem (I couldn't even filter by __month or __day) until I disabled USE_TZ. Again, may not be ideal for your case, but it should get __date working again.
回答2:
I have a visitor model. In this model I filtered data through date not time and it's working.
models.py
Visitor(models.Model):
timestamp = models.DateTimeField(_('Login Date Time'), auto_now=True)
os_info = models.CharField(_('OS Information'), max_length=30, null=True)
views.py
import datetime
visitor = Visitor.objects.filter( timestamp__lte=datetime.datetime.now().date())
print visitor
Output:
<Visitor: Windows 10>, <Visitor: Windows 10>]
Use above way to filter data from date.
回答3:
You can use multiple ways to filter out based on date. Here are some of those
import datetime
custom_date = datetime.date(2005, 1, 1)
Entry.objects.filter(pub_date__contains=custom_date) #Fastest in terms of performance
Entry.objects.filter(pub_date__startswith=custom_date)
Entry.objects.filter(pub_date__gte=custom_date)
来源:https://stackoverflow.com/questions/42701151/filtering-django-datetimefield-date-not-working