【问题标题】:Django DateTimeField defaultDjango DateTimeField 默认
【发布时间】:2015-11-24 23:50:01
【问题描述】:

Django 中的以下模型(Python 3.4、Django 1.7.4 w/PostgreSQL)需要其 DateTimeField 的默认值:

from django.utils import timezone as django_tz 

class AvailabilityRuleOnce(AvailabilityRule):
    class Meta:
        app_label = 'configuration'

    objects = AvailabilityRuleOnceManager()

    starting_time = django_models.DateTimeField(
        'Starting time for the rule', default=django_tz.now, blank=True
    )
    ending_time = django_models.DateTimeField(
        'Ending time for the rule', default=django_tz.now, blank=True
    )

尝试应用迁移时,抛出以下异常:

django.db.utils.ProgrammingError: column "ending_time" cannot be cast automatically to type timestamp with time zone
HINT:  You might need to specify "USING ending_time::timestamp with time zone".

在 Django 文档中,他们推荐了此选项,我还尝试了其他可以在线找到的选项,例如添加“auto_now_add=True”,但它也不起作用。我做错了什么?

【问题讨论】:

  • 真正的问题是 Django 的迁移不会擦除带有数据字段的列,这在更新默认值之前是必需的。

标签: python django postgresql django-models


【解决方案1】:

auto_now_true唯一 将字段设置为在创建时更新的方法,as the documentation states

auto_now_addauto_nowdefault 选项是互斥的。这些选项的任何组合都会导致错误。

如果auto_now_true 不起作用,您需要提出一个错误。

【讨论】:

  • 这行得通,但实际问题是我必须通过注释掉代码中模型中的字段来从数据库中删除原始字段,然后使用新的字段定义进行迁移和迁移。我得到的具体例外是因为数据库中的旧现有字段无法转换为迁移文件中的新定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 2018-03-25
  • 2018-01-29
  • 2013-07-08
  • 2019-01-10
相关资源
最近更新 更多