1

我在 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 的发行说明中,他们为时区简单的数据库添加了一个 TIME_ZONE 属性(比如我运行测试的 SQLite)。我尝试将我的时区添加到数据库配置中,但问题仍然存在。有任何想法吗?这是我在 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
        }
4

1 回答 1

0

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

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

于 2016-11-28T19:00:06.727 回答