Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...