2015-11-24 133 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