Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering django DatetimeField__date not working

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.

like image 759
Roel Avatar asked Mar 09 '17 16:03

Roel


People also ask

How do I change the default date in Django?

If you want to be able to modify this field, set the following instead of auto_now_add=True : For DateField : default=date.today - from datetime.date.today() For DateTimeField : default=timezone.now - from django.utils.timezone.now()

How does Django filter work?

Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this.

What is date/time field in Django?

DateTimeField is a date and time field which stores date, represented in Python by a datetime. datetime instance. As the name suggests, this field is used to store an object of datetime created in python. The default form widget for this field is a TextInput .


1 Answers

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.

like image 139
J. Morris Avatar answered Sep 18 '22 21:09

J. Morris