preserve data when migrating ForeignKey to ManyToManyField

320 views
Skip to first unread message

A Lee

unread,
Jul 14, 2015, 5:32:46 PM7/14/15
to django...@googlegroups.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?

Erik Cederstrand

unread,
Jul 15, 2015, 7:19:31 AM7/15/15
to Django Users
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


Reply all
Reply to author
Forward
0 new messages