0

I hava a django applcation where there are two models Desination and Package, where Package has a foriegn key field to Destination. Now after many days clients wants it to be m2m. I have to change that and also preserve the data at the same time.

My models:

class Destination(models.Model):
    name = models.CharField(max_length=255, unique=True)
    .................../

class Package(models.Model):
    # destination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name='package')
    destinations = models.ManyToManyField(Destination,related_name='packages')
    ....................../

Here I changed the fk field to m2m with the following way:

from __future__ import unicode_literals

from django.db import models, migrations



def make_many_destinations(apps, schema_editor):
    """
        Adds the Destination object in Package.destination to the
        many-to-many relationship in Package.destinations
    """
    Package = apps.get_model('packages', 'Package')

    for abc in Package.objects.all():
        abc.destinations.add(abc.destination)

class Migration(migrations.Migration):

    dependencies = [
        ('packages', '0006_package_destinations'),
    ]

    operations = [
        migrations.RunPython(make_many_destinations),
    ]

I did exactly the same as this

Django data migration when changing a field to ManyToMany

I had to create a custom migration file (above), write a function, and then run migrate. In my local development, it works perfectly. The field is changed to m2m and there are data as well.

We are having aws as a production server. I did the commits and did eb deploy, then went to the production database and created the new table for m2m relationships. I created the table adding all indexes and keys and saved it. Then I went to live backend and checked, there is a new field of m2m but the fields data are all gone. I use Heidi SQL for accessing live database.

How to solve this? We can bring back the old db with data as there is backup. But How to proceed now?

I am thinking of writing sql query in live db for this

for abc in Package.objects.all():
            abc.destinations.add(abc.destination)

I think we have to use insert. But i am not sure how??

Reactoo
  • 630
  • 6
  • 20

0 Answers0