【问题标题】:How to change the "timestamp without time zone" to "timestamp with time zone" using Django models using migrations?如何使用迁移的 Django 模型将“没有时区的时间戳”更改为“有时区的时间戳”?
【发布时间】:2021-05-08 12:18:58
【问题描述】:
class test(models.Model):
mobile_last_login = models.DateTimeField()
我需要将“mobile_last_login”字段的“timestamp without time zone”更改为“timestamp with time zone”。
【问题讨论】:
标签:
python
django
postgresql
django-models
pgadmin
【解决方案1】:
如果您在设置中设置了USE_TZ = True,则无法将时区添加到DateTimeField - Django 以UTC 存储日期时间,否则设置天真日期时间。如果设置了USE_TZ,那么Django会自动应用时区偏移量,根据你的设置,从DB中获取数据。
如果您确实需要存储时区,可能最简单的解决方案是将其存储为单独的字段:
import pytz
class test(models.Model):
TIMEZONE_CHOICES = tuple(zip(pytz.all_timezones, pytz.all_timezones))
mobile_last_login = models.DateTimeField()
timezone = models.CharField(max_length=32, choices=TIMEZONE_CHOICES, default=str(pytz.utc))