Reputation: 1197
I want to filter current month data. I tried this.
this_month = datetime.datetime.now().month
products = Product.objects.filter(date_added__month=this_month)
But, this only works with USE_TZ = False
. if I change to USE_TZ = True
. my filter query not working.
model
date_added = models.DateTimeField(auto_now=True)
Upvotes: 2
Views: 8672
Reputation: 1299
It's pretty old question, but I think my answer can help people searching for it.
First of all, when USE_TZ=True, we should always use django.utils.timezone.now()
instead of datetime.datetime.now()
. (ref)
Django documentation says:
When USE_TZ is True, datetime fields are converted to the current time zone before filtering. This requires time zone definitions in the database.
It also 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
Now I can use <datetime>__month
filter even if USE_TZ = True
Do comment if you need further explanation.
added info about django.utils.timezone on suggestion of Jerzyk yesterday
Upvotes: 4