python - Django 查询集 : cannot filter by current week when USE_TZ is enabled

标签 python mysql django

我使用的是 Django 2.1,其中 USE_TZ = TrueTIME_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 databaseshttps://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/

相关文章:

python - 获取两个列表之间的差异

python - python += 字符串连接是不好的做法吗?

python - 仅针对某些应用程序收集静态信息

jquery - django 管理和自动完成灯 : Select2: An instance of jQuery or a jQuery-compatible library was not found

python - 在 Django loaddata 中,它会抛出 json 格式的错误,但对于 yaml 格式却可以正常工作,为什么?

python - 高 CPU 负载(来自其他应用程序)会影响 python 性能/准确性吗?

python - 在 LARGE 字符串中查找子字符串

Python编码与mysql

c# - 如何从 Form 类中调用方法?

php搜索一个mysql字符串结果