OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Did I write data migration for data type change in a correct way?

  • Thread starter Thread starter Coder4Fun250
  • Start date Start date
C

Coder4Fun250

Guest
Say, I have a model TestModel:

Code:
class TestModel(models.Model):
    field1 = models.CharField(max_length=255)
    field2 = models.IntegerField()

    def __str__(self):
        return f"{self.field1}"

But I need to change the type of field2 to Text now. In order not to lose the data in TestModel model, I need to write a data migration.

So I create a new model NewTestModel:

Code:
class NewTestModel(models.Model):
    field1 = models.CharField(max_length=255)
    field2 = models.TextField()

    def __str__(self):
        return f"{self.field1}"

Run python manage.py makemigrations command

In 0006_newtestmodel.py migration file I add copy_data function and run it using migrations.RunPython(copy_data)

Code:
from django.db import migrations, models

def copy_data(apps, database_schema):
    TestModel = apps.get_model("data_migrations", "TestModel")
    NewTestModel = apps.get_model("data_migrations", "NewTestModel")

    for old_object in TestModel.objects.all():
        new_object = NewTestModel(
            field1 = old_object.field1,
            field2 = old_object.field2
        )
        new_object.save()


class Migration(migrations.Migration):

    dependencies = [
        ('data_migrations', '0005_testmodel'),
    ]

    operations = [
        migrations.CreateModel(
            name='NewTestModel',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('field1', models.CharField(max_length=255)),
                ('field2', models.TextField()),
            ],
        ),
        migrations.RunPython(copy_data)
    ]

Then I delete TestModel model and run the migration commands.

After that I rename NewTestModel to TestModel and once again run the migration commands.

Everything worked out as it was supposed to.

Did I do it right?
<p>Say, I have a model TestModel:</p>
<pre><code>class TestModel(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.IntegerField()

def __str__(self):
return f"{self.field1}"
</code></pre>
<p>But I need to change the type of field2 to Text now. In order not to lose the data in TestModel model, I need to write a data migration.</p>
<p>So I create a new model NewTestModel:</p>
<pre><code>class NewTestModel(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.TextField()

def __str__(self):
return f"{self.field1}"
</code></pre>
<p>Run <code>python manage.py makemigrations</code> command</p>
<p>In 0006_newtestmodel.py migration file I add copy_data function and run it using <code>migrations.RunPython(copy_data)</code></p>
<pre><code>from django.db import migrations, models

def copy_data(apps, database_schema):
TestModel = apps.get_model("data_migrations", "TestModel")
NewTestModel = apps.get_model("data_migrations", "NewTestModel")

for old_object in TestModel.objects.all():
new_object = NewTestModel(
field1 = old_object.field1,
field2 = old_object.field2
)
new_object.save()


class Migration(migrations.Migration):

dependencies = [
('data_migrations', '0005_testmodel'),
]

operations = [
migrations.CreateModel(
name='NewTestModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('field1', models.CharField(max_length=255)),
('field2', models.TextField()),
],
),
migrations.RunPython(copy_data)
]
</code></pre>
<p>Then I delete TestModel model and run the migration commands.</p>
<p>After that I rename NewTestModel to TestModel and once again run the migration commands.</p>
<p>Everything worked out as it was supposed to.</p>
<p><strong>Did I do it right?</strong></p>
 

Latest posts

M
Replies
0
Views
1
MOHAMED AMIIN ABDI AADAN
M
Top