python - DateTimeField 设置为默认字段

标签 python django postgresql

以下模型的日期字段需要一个默认值:

from django.utils import timezone as django_tz 
import psycopg2

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”,但它也不起作用。我做错了什么?

最佳答案

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

The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error.

如果 auto_now_true 不工作,您需要提出错误。

关于python - DateTimeField 设置为默认字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33906078/

相关文章:

sql - 使用 ARRAY_AGG 获取列中的第一个非 NULL 值是否浪费?

python - 从头 Python 构建包含数据的表

python - 如何仅记录数据框中的非零值并将 O 替换为 NA?

python - 从明亮的彩条下发现图像

django - 在 settings.py 中为 Travis CI 配置数据库部分

sql - 将复合类型的数组传递给存储过程

postgresql - 使用 NetTopologySuite 与 EF Core 和 postgis 计算两点之间的地理距离

python - 为什么我会收到 KeyError : 'scheduler' when trying to run a celery beat?

Django 套装 : ImportError: No module named suit

python - 如何从 Django 中的查询集中删除前 N 项