Question: How to convert Foreign Key Field into Many To Many Field without disturbing existing data in the database?

Question

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

Answers 2
Added at 2016-12-30 06:12
Tags
Question

My code snippet is as follows :

class Table1(models.Model):
    name = models.CharField(max_length=20)

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

Consider both the table has data in the database. What is the possible way to convert the Foreign Key Field(in Table2) into Many To Many Field without losing existing data in the database?

*Note: I am using Django 1.6.4(not using Django migrations)*
Answers
nr: #1 dodano: 2016-12-30 06:12

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.

nr: #2 dodano: 2016-12-30 07:12
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
Source Show
◀ Wstecz