【问题标题】:column "date" cannot be cast automatically to type timestamp with time zone django/postgres列“日期”不能自动转换为带有时区 django/postgres 的时间戳
【发布时间】:2017-05-14 14:25:49
【问题描述】:

有一个 date charfield ,当我之前将日期保存为字符串时。但现在我将字段从 charfield 更改为 datetimefield 并删除了所有以前的数据。

date = models.DateTimeField(default=timezone.now)

Localy 它工作正常,但在生产中尝试迁移时会引发以下错误。我删除了列、模型、注释和取消注释、删除并再次创建了字段、返回到以前的迁移并再次迁移,但所有这些都没有帮助。

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

如何正确解决问题?使用 django 1.8、python 2.7 和 postgres

【问题讨论】:

    标签: python django postgresql date


    【解决方案1】:

    如果您的列不能从新列的原始类型完全转换,请考虑删除旧列并创建一个新列:

    • 注释掉模型中的列字段
    • makemigration(将为此字段生成删除迁移)-> 您将删除所有列数据
    • migrate 在模型中留下注释再次运行 makemigration (现在将生成一个新的迁移与新的列与新的 数据类型)
    • 再次运行 migrate 以应用更改

    如果您的字段很少,这很有效,但如果您有很多字段要转换,我建议为此编写特定的数据迁移

    【讨论】:

      【解决方案2】:

      对于尝试将整数列转换为时间戳时在 Google 上发现此问题的任何人:

      ALTER TABLE my_table
      ALTER COLUMN my_column
      TYPE timestamp with time zone
      USING to_timestamp(my_column);
      

      【讨论】:

        【解决方案3】:

        在 postgres shell 中运行:

        ALTER TABLE table_name ALTER COLUMN col_name TYPE timestamp with time zone USING col_name::timestamp with time zone
        

        【讨论】:

        • 有没有不中断的数据库解决方案?会不会有什么问题?
        • 如果您的列完全可转换为日期并且没有任何无效数据,则不会出现任何问题
        猜你喜欢
        • 2021-01-05
        • 2019-08-22
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 2015-10-07
        • 2022-01-09
        • 2018-02-08
        • 2020-02-05
        相关资源
        最近更新 更多