Django:在models.py中将TimeField更改为DateTimeField [英] Django: Change TimeField to DateTimeField in models.py

查看:406
本文介绍了Django:在models.py中将TimeField更改为DateTimeField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的models.py中,我有一些具有这种属性的模型:

In my models.py, i have some models with this kind of attributes:

timestamp = models.TimeField(default=0)

我想将它们更改为:

timestamp = models.DateTimeField(default=0)

使用

python manage.py schemamigration app --auto 

首先起作用。
但是

works in first instance. But

python manage.py migrate app

导致此错误:

django.db.utils.ProgrammingError: column "timestamp" cannot be cast to type timestamp with time zone

的时间戳,所以我需要以某种方式铸造可能。对于每个没有日期的时间,我想设置一个默认日期(例如昨天)。我怎样才能做到这一点?
我只在SO上找到,这对都是因为那个错误。
BTW:我正在使用postgres和python3。

So i somehow needs to make this casting possible. For every time without date i want to set a default date (e.g. yesterday). How can i do this? I only found this on SO, which does not help at all because of that error. BTW: I am using postgres and python3.

感谢您的帮助!

我可以在数据库上直接使用SQL(没有南方) ),如果这样更容易

It is okay for me to use SQL direct on the database (without south) if that's easier

推荐答案

那是因为时间无法转换(广播) )到PostgreSQL中的 timestamp (与时区无关的变体)。 F.ex.这也会失败:

That's because time cannot be converted (casted) to timestamp (neither their time-zone related variants) in PostgreSQL. F.ex. this will also fail:

SELECT 'now'::time::timestamp

在这种情况下,应在 ALTER中使用 USING 子句TABLE 语句(如果可以直接编辑):

In these cases, you should use the USING clause in your ALTER TABLE statement (if you can edit it directly):

ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
ALTER [ COLUMN ] column_name
[ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]

您的查询看起来像是,例如:

Your query will look like, f.ex.:

ALTER TABLE "my_model"
ALTER COLUMN "column_name"
SET DATA TYPE TIMESTAMP WITH TIME ZONE USING 'yesterday'::date + "column_name"

这篇关于Django:在models.py中将TimeField更改为DateTimeField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆