升级到 Django 1.9 后的时区问题



我在 Django 1.8.5 中有一个测试,它通过了。这是

def test_user_returns_from_vacation_correctly_increments_review_timestamps(self):
        self.user.profile.on_vacation = True
        now = timezone.now()
        an_hour_ago = now - timedelta(hours=1)
        two_hours_ago = now - timedelta(hours=2)
        self.user.profile.vacation_date = an_hour_ago
        self.user.profile.save()
        self.review.last_studied = two_hours_ago
        self.review.save()
        previously_studied = self.review.last_studied
        user_returns_from_vacation(self.user)
        rev = UserSpecific.objects.get(id=self.review.id) #<---This is the line causing the error!
        print(rev)
        self.assertNotEqual(rev.last_studied, previously_studied)
        self.assertAlmostEqual(rev.last_studied, an_hour_ago, delta=timedelta(seconds=1))

但是,在升级到 Django 1.9 时,此测试会导致此错误:

Error
Traceback (most recent call last):
/pytz/tzinfo.py", line 304, in localize
etc etc
    raise ValueError('Not naive datetime (tzinfo is already set)')
ValueError: Not naive datetime (tzinfo is already set)

以下是相关的user_returns_from_vacation代码:

def user_returns_from_vacation(user):
    """
    Called when a user disables vacation mode. A one-time pass through their reviews in order to correct their last_studied_date, and quickly run an SRS run to determine which reviews currently need to be looked at.
    """
    logger.info("{} has returned from vacation!".format(user.username))
    vacation_date = user.profile.vacation_date
    if vacation_date:
        users_reviews = UserSpecific.objects.filter(user=user)
        elapsed_vacation_time = timezone.now() - vacation_date
        logger.info("User {} has been gone for timedelta: {}".format(user.username, str(elapsed_vacation_time)))
        updated_count = users_reviews.update(last_studied=F('last_studied') + elapsed_vacation_time)
        users_reviews.update(next_review_date=F('next_review_date') + elapsed_vacation_time)
        logger.info("brought {} reviews out of hibernation for {}".format(updated_count, user.username))
    user.profile.vacation_date = None
    user.profile.on_vacation = False
    user.profile.save()

更新:如果我删除 F() 表达式,并用 for 循环替换它们,此错误就会消失。这样:

    for rev in users_reviews:
        lst = rev.last_studied
        nsd = rev.next_review_date
        rev.last_studied = lst + elapsed_vacation_time
        rev.next_review_date = nsd + elapsed_vacation_time
        rev.save()

我在 1.9 的发行说明中注意到,他们为时区初始数据库(如 SQLite,这是我运行测试时使用的)添加了 TIME_ZONE 属性。我尝试将时区添加到数据库配置中,但问题仍然存在。有什么想法吗?以下是我在 settings.py 中与时区相关的设置

MY_TIME_ZONE = 'America/New_York'
TIME_ZONE = MY_TIME_ZONE
DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
            'TIME_ZONE': MY_TIME_ZONE
        }

最终,在核心开发人员遇到麻烦之后,我发现这确实是一个错误,特别是在使用 SQLite 时。它记录在这里,但仍未修复:

https://code.djangoproject.com/ticket/27544

相关内容

  • 没有找到相关文章

最新更新