Django,Postgres - 列不能自动转换为整型 [英] Django, Postgres - column cannot be cast automatically to type integer
问题描述
在我的数据库中我有列:
currency = models.CharField(max_length = 10,blank = True,null =真的)
我想从 CharField
到 IntegerField
。所以在 models.py
中,我改变了这一点:
currency = models。 IntegerField(blank = True,null = True)
然后我进行迁移: python manage.py makemigrations
和 python manage.py migrate
。之后,这个动作会出现错误:
django.db.utils.ProgrammingError:列currency不能自动转换为整型
提示:指定一个USING表达式来执行转换。
之后,在pgAdmin3控制台中,我进行了以下更改:
ALTER TABLE my_table ALTER COLUMN货币类型整数USING(currency :: integer);
但是我仍然收到这个错误,我试图改变所有回来,但错误不会消失。我要做的是逃避这个错误。谢谢
我认为django迁移不执行转换,我查看文档,但是我没有发现有关列转换的任何事情。
-
如果现有数据对您不重要,可以删除该列并创建一个新的
- 第一步从您的模型中删除货币并应用迁移
- 再次添加具有新定义的货币,并再次应用迁移
-
如果要保留数据,则需要为新列添加不同的名称,并将旧列用作临时列以在转换期间保存数据
重要提示: Postgresql在最近的版本中更强烈地键入, a href =http://www.postgresql.org/message-id/20051229211409.GA9834 @ winnie.fuhr.orgrel =nofollow>这里一些投票可能无法在PosgreSQL中工作,除非它被明确地完成。它需要更具体的类型。因此,您必须根据您的价值确定选择的权利:
alter table my_table alter column货币类型bigint使用货币:: bigint
pre>
或者可能:
alter table my_table alter column currency type数字(10,0)使用货币:数字
In my database i have column:
currency = models.CharField(max_length=10, blank=True, null=True)
I want to change this column from
CharField
toIntegerField
. So inmodels.py
i change this:currency = models.IntegerField(blank=True, null=True)
then i made migrations:
python manage.py makemigrations
andpython manage.py migrate
. After that actions it rise error:django.db.utils.ProgrammingError: column "currency" cannot be cast automatically to type integer HINT: Specify a USING expression to perform the conversion.
After that in pgAdmin3 console i made this changes:
ALTER TABLE my_table ALTER COLUMN currency TYPE integer USING (currency::integer);
But i still got that error, I tried to change all back, but error doesn't disappear. What i have to do to escape this error. Thank you
解决方案I think django migrations does not perform casting, I looked in the documentation but I did not find any thing about column casting.
if the existing data is not that important for you, you can delete the column and create a new one
- first step remove currency from you model and apply migration
- add again the currency with the new definition and apply again the migration
if you want to keep your data, you need to give your new column a different name and use the old column as a temporary column to hold the data during the transition.
Important: Postgresql is more strongly typed in recent versions, and as explained here some casting may not work in PosgreSQL unless it's explicitly done. And it required to be more specific about the type. So you have to make the right choice based on your values:
alter table my_table alter column currency type bigint using currency::bigint
or maybe:
alter table my_table alter column currency type numeric(10,0) using currency::numeric
这篇关于Django,Postgres - 列不能自动转换为整型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!