Changing a foreign key to the many-to-many field

This recipe is a practical example of how to change a many-to-one relation to many-to-many relation, while preserving the already existing data. We will use both schema and data migrations for this situation.

Getting ready

Let's consider that you have the Idea model with a foreign key pointing to the Category model, as follows:

# demo_app/models.py # -*- coding: UTF-8 -*- from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Category(models.Model): title = models.CharField(_("Title"), max_length=200) def __str__(self): return self.title ...

Get Web Development with Django Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.