I have a Django application in which I want to change a field from a ForeignKey to a ManyToManyField. I want to preserve my old data. What is the simplest/best process to follow for this? If it matters, I use sqlite3 as my database back-end.
If my summary of the problem isn't clear, here is an example. Say I have two models:
class Author(models.Model):
author = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=100)
Say I have a lot of data in my database. Now, I want to change the Book model as follows:
class Book(models.Model):
author = models.ManyToManyField(Author)
title = models.CharField(max_length=100)
I don't want to "lose" all my prior data.
What is the best/simplest way to accomplish this?
Ken
Probably the best and easiest thing you should do would be:
Create the Many to many field with a different name say
write a small function to convert foreignkey values to M2M values:
Once it is run, you can delete the author field from the table and run migration again.
I realize this question is old and at the time the best option for Data Migrations was using South. Now Django has its own
migrate
command, and the process is slightly different.I've added these models to an app called
books
-- adjust accordingly if that's not your case.First, add the field to
Book
and arelated_name
to at least one, or both of them (or they'll clash):Generate the migration:
Now, create an empty migration to hold the migration of the data itself:
And add the following content to it. To understand exactly how this works, check the documentation on Data Migrations. Be careful not to overwrite the migration dependency.
Now remove the
author
field from the Model -- it should look like this:Create a new migration for that, and run them all:
And that's it. The authors previously available at
book.author
now should be in the queryset you get frombook.authors.all()
.