Skip to main content
 首页 » 编程设计

python之Django 过滤当月数据

2024年08月27日29lyhabc

我想过滤当前月份的数据。我试过了。

this_month = datetime.datetime.now().month 
products = Product.objects.filter(date_added__month=this_month) 

但是,这只适用于 USE_TZ = False 。如果我更改为 USE_TZ = True 。我的过滤器查询不起作用。

模型

date_added = models.DateTimeField(auto_now=True) 

请您参考如下方法:

这是一个很老的问题,但我认为我的回答可以帮助人们搜索它。

首先,当USE_TZ=True时,我们应该总是使用django.utils.timezone.now()而不是 datetime.datetime.now() . ( ref )

Django 文档 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.

它还给出了instruction将时区定义安装到数据库:

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.

在我的例子中:mysql 和 Mac Os,下面的命令解决了问题:

sudo mysql_tzinfo_to_sql /usr/share/zoneinfo/ | mysql -u root mysql 

现在我可以使用 <datetime>__month过滤即使 USE_TZ = True

如果您需要进一步解释,请发表评论。

编辑

根据 Jerzyk yesterday 的建议添加了有关 django.utils.timezone 的信息