我使用的是 Django 2.1,其中 USE_TZ = True
和 TIME_ZONE = 'UTC'
。
这是我的模型 DateTimeField:
create_date = models.DateTimeField(_('date created'), null=True, auto_now_add=True)
我正在尝试根据周数获取当前周的结果。我尝试了以下方法:
today = timezone.now()
current_week_num = today.isocalendar()[1]
week_results = MyModel.objects.filter(create_date__week=current_week_num).count()
当数据库中有记录时,它总是返回 0。如果我设置 USE_TZ = False ,它就可以正常工作。我正在使用 MySql 数据库。
有什么想法吗?
更新:
问题出在 MySQL time_zone 表为空!我不得不跑: mysql_tzinfo_to_sql/usr/share/zoneinfo 问题就消失了!
最佳答案
部分Other databases
在https://docs.djangoproject.com/en/2.1/topics/i18n/timezones/#database如果您的数据库不是 Postgres,您可能会感兴趣。
Other backends store datetimes without time zone information. If you switch from USE_TZ = False to USE_TZ = True, you must convert your data from local time to UTC – which isn’t deterministic if your local time has DST.
关于python - Django 查询集 : cannot filter by current week when USE_TZ is enabled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53812936/