Can someone explain to me why the following filters are not working at the month and day level? Filtering by year seems to work, but not the other two.
>>> clicks.count()
36
>>> date = clicks[0].created
>>> date.month
2
>>> date.year
2014
>>> date.day
1
>>> clicks.filter(created__month=2)
[]
>>> clicks.filter(created__month=02)
[]
>>> clicks.filter(created__month='02')
[]
>>> clicks.filter(created__month='2')
[]
>>> clicks.filter(created__month=date.month)
[]
>>> clicks.filter(created__day=date.day)
[]
A quick update to demonstrate that I am getting the same behavior before creating and dealing with a queryset:
>>> clicks = PreviewClick.objects.filter(created__month = 2)
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = 02)
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = '02')
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = '2')
>>> clicks.count()
0
Here's more food for thought:
>>> clicks = PreviewClick.objects.all()
>>> counter = 0
>>> for click in clicks:
... if click.created.month == 2:
... counter += 1
...
>>> counter
35
I was seeing exactly the same behaviour as you.
If you check the documentation for 1.6 and the month queryset. They have added the following paragraph:
"When USE_TZ is True, datetime fields are converted to the current time zone before filtering. This requires time zone definitions in the database."
If you change the following line in your settings to False, then you should start getting the data back that you're expecting.
USE_TZ = False
@Simon Wilder perfectly answer why it's not working, here is how you can actually solve it without disabling TZ support in django
Django document give instruction to install time zone definition to database:
SQLite: install
pytz
— conversions are actually performed in Python.PostgreSQL: no requirements (see Time Zones).
Oracle: no requirements (see Choosing a Time Zone File).
MySQL: install
pytz
and load the time zone tables withmysql_tzinfo_to_sql
.
In my case : mysql and Mac Os, following command solve the problem:
sudo mysql_tzinfo_to_sql /usr/share/zoneinfo/ | mysql -u root mysql
Your syntax is incorrect. It should be:
Clicks.objects.filter(created__month=2)
(you left off the 'objects' manager)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With