简体   繁体   中英

Django filter current month data

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)

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 with mysql_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.

edit

added info about django.utils.timezone on suggestion of Jerzyk yesterday

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM