How to convert a foreign key field into many fields without breaking existing data in the database?

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 that the table has data in the database. What is a possible way to convert a field Foreign Key Field(in Table2)to Many To Manywithout losing existing data in the database?

*Note: I am using Django 1.6.4(not using Django migrations)*
+4
source share
2 answers

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

0
source
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
0
source

Source: https://habr.com/ru/post/1665288/


All Articles