2015-11-24 132 views
2

在Django以下模型(Python的3.4,Django的1.7.4瓦特/ PostgreSQL的)需要为它DateTimeField字段的默认值:Django的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 =真”,但它不工作或者其他选项。我究竟做错了什么?

+0

真正的问题是,Django的迁移不会使用datafield擦除列,在更新默认值之前这是必需的。 – Ricardo

回答

1

auto_now_true设置领域上创造更新的唯一方式as the documentation states

选项auto_now_addauto_now,并default是互斥的。这些选项的任何组合都会导致错误。

如果auto_now_true不工作,你需要提高的错误。

+1

这很有效,但实际的问题是,我必须通过注释代码中模型中的字段来删除数据库中的原始字段,然后使用字段的新定义再次迁移和迁移。我得到的特定例外是因为数据库中旧的现有字段无法转换为迁移文件中的新定义。 – Ricardo