2016-05-23 32 views
1

我在Django 1.8.5中通过测试。这里是升级到Django 1.9后的时区问题

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 
     } 
+0

可能想看看这个 - https://docs.djangoproject.com/en/1.9/topics/i18n/timezones/ –

+0

我读过这个,我也读过1.8版本。由于没有区别,这并不能解释为什么我的测试在一个版本中失败,而不是另一个版本。 – Tadgh

回答