setings.py:-
USE_TZ = True
TIME_ZONE = 'America/Chicago'
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
# time zone related field
user_time_zone = models.CharField(max_length=255, null=True, blank=True)
time_difference = models.CharField(max_length=255, null=True, blank=True)
client_date = models.DateTimeField(null=True, blank=True)
display_date = models.DateTimeField(null=True, blank=True)
MyModel object create
MyModel.objects.create(user_time_zone=form.cleaned_data['prefer_time_zone'])
Signal called after the MyModel is created
def update_time_zone(sender, instance, created, **kwargs):
if created:
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
now_utc = instance.created_at
if instance.user_time_zone:
if instance.user_time_zone == 'US/Alaska':
alaska = now_utc.astimezone(timezone('US/Alaska'))
print "alaska is_aware", is_aware(alaska)
print "alaska is_naive", is_naive(alaska)
instance.client_date = alaska
instance.display_date = alaska
instance.time_difference = alaska.strftime(fmt).split(" ")[2]
instance.save()
print "alaska now utc", type(now_utc)
print "alaska type", type(alaska)
print "alaska", alaska
# At here i got updated value but when i see inside
# postgres database value is not updated
print "instance.client_date", instance.client_date
print "us/alaska", alaska.strftime(fmt)
signals.post_save.connect(update_time_zone, sender=MyModel)
instance.created_at = 2016-02-06 21:42:22.552000+00:00
alaska = 2016-02-06 12:42:22.552000-09:00
问题:-
将 instance.created_at 转换为“US/Alaska”后,输出为 2016-02-06 12:42:22.552000-09:00。但是当我像上面的信号一样使 client_date 和 display_date 等于 alaska 时,它没有保存我新更新的 alaska 值,而是通过添加 5 小时来按 instance.created_at 值更新 client_date 和 display_date。我需要按阿拉斯加时区更新 client_date 和 display_date。
当我调用 instance.save() 时,它在 postgres 数据库中无效。什么问题?为什么它不更新阿拉斯加值?有没有像 django force 这样的东西不更新新值,而是使用默认时区更新值?