> Den 14/07/2015 kl. 23.32 skrev A Lee <anonymous...@gmail.com>:
> 
> I'd like to change a ForeignKey field into a ManyToManyField, preserving 
> existing data by creating entries in the many-to-many through table. Running 
> makemigrations after changing the model class creates a migration that 
> executes a RemoveField on the existing ForeignKey field and then an AddField 
> on the new ManyToManyField, which destroys any existing ForeignKey data.
> 
> I ended up implementing this by creating three migrations:
> 
> 1. schema migration: create the new ManyToManyField
> 2. data migration: copy existing ForeignKey data into the ManyToManyField
> 3. schema migration: remove the ForeignKey field and rename the 
> ManyToManyField
> 
> Is there a simpler way to do this type of schema change?

No. AFAIK, this is the recommended and most robust and flexible way of making 
non-trivial changes to a model field definition.

If you have lots of data to migrate, you may need to optimize the data 
migration with e.g. raw SQL instead of the naive:

   for obj in MyModel.objects.all():
      obj.my_m2m.add(obj.my_fk)

Erik


-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/52FB9F20-D170-4787-AB16-979008008A1A%40cederstrand.dk.
For more options, visit https://groups.google.com/d/optout.

Reply via email to