Friday, November 30, 2012

Re: Drop foreign key, add another - keep data

On Fri, Nov 30, 2012 at 11:56 AM, Peter Edström <edstromp@gmail.com> wrote:
> Hello,
>
> I'd like to drop a ForeignKey-field and add another using south (mysql
> database), but it won't work. Googling it takes me not far, but it seems to
> be a problem with dropping foreign key constraints with InnoDB.
> What is the recommended way ot dropping a ForeignKey-field, and adding
> another?
>
> Say the model looks like this:
>
>> class Model1(models.Model):
>>
>> test = models.ForeignKey(Model2)
>
>
> And I won't to change it to:
>
>> class Model1(models.Model):
>>
>> test2 = models.ForeignKey(Model3)
>
>
> Right now I don't really care if I lose data, but for future reference I'd
> prefer a method that keeps it.
>
> Thank you.
>

How are you trying to do it? There should be several migrations:

1) A schema migration to add the new foreign key, which should be
nullable at this point
2) A data migration to move the old data into the new column
3) A schema migration to drop the nullability of the new foreign key
4) A schema migration to drop the old foreign key

You may not need as many migrations if you do not need to migrate the
old data over, or if the new foreign key is allowed to be null.

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment