Django 1.7 migrate for postgres fails: Charfield to ForeignKey

1,116 views
Skip to first unread message

Martin Kapfhammer

unread,
Feb 20, 2015, 4:30:33 PM2/20/15
to django...@googlegroups.com
First I created a CharField:
     ('currency', models.CharField(max_length=30)),

In a later migration I changed it to a foreign key field:

field=models.ForeignKey(to='web.Currency'),

It worked on a local MySql instance, but not on Postgres on Heroku:
django.db.utils.ProgrammingError: column "currency_id" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion.

If I do the following manually, I can continue:

alter table web_financialdata drop column currency;
alter table web_financialdata add column currency integer;

Should I add this via RunSQL between the migrations. If so, how? Or is there a better way?

Thanks,
Martin





George Silva

unread,
Feb 20, 2015, 5:16:48 PM2/20/15
to django-users
The deal here is that the model Currency has an ID, which is well, integer.

Your data that is already on that column, is char (original field). If you are not in production, I would recommend dropping the field (comment the code), make migrations and apply. that will remove the currency column. Then add the new column, make migrations and apply.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bdde39c8-a81a-4228-bb68-cbebb675d729%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
George R. C. Silva
SIGMA Consultoria
----------------------------

Martin Kapfhammer

unread,
Feb 20, 2015, 7:15:18 PM2/20/15
to django...@googlegroups.com
Yep, I can drop the column and create a new one as integer.
The only problem I have is that creating the field as a char was in migration number 0020, changing it to a foreign key was in migration number 0028 and now I have already 0036 migrations. Therefore I have to "hang in" the dropping and adding code between 0020 and 0028. How can I do this? I can write the migration files by hand, but what is the logic to hang it in e.g. before 0028 with already a 0027 existing.

What's best practice here?

George Silva

unread,
Feb 20, 2015, 11:07:04 PM2/20/15
to django-users

check merge migrations. some migrations the framework will combine whenever possible.

Martin Kapfhammer

unread,
Feb 21, 2015, 9:25:18 AM2/21/15
to django...@googlegroups.com
Alright, so I uncommented the creation of the CharField and changed the AlterField to an AddField operation. Worked! :)

Thank you
Reply all
Reply to author
Forward
0 new messages