[Django]-How to convert Foreign Key Field into Many To Many Field without disturbing existing data in the database?

0👍

You need to do it in a couple of steps. First add the M2M-field and copy your data. Next change your application logic to use the new field. Finally you can remove the old ForeignKey-field.

👤skoll

0👍

class Table2(models.Model):
    name = models.CharField(max_length=20)
    description = models.TextField()
    table1 = models.ForeignKey(Table1)
    table1_new = models.ManyToManyField(Table1, related_name='_')

# python manage.py makemigrations && python manage.py migrate && python manage.py shell
# get things done by a for loop


class Table2(models.Model):
    name = models.CharField(max_length=20)
    description = models.TextField()
    table1_new = models.ManyToManyField(Table1, related_name='_')

# python manage.py makemigrations && python manage.py migrate


class Table2(models.Model):
    name = models.CharField(max_length=20)
    description = models.TextField()
    table1 = models.ManyToManyField(Table1)

# python manage.py makemigrations && python manage.py migrate

Leave a comment