Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are the historical models?

Tags:

django

model

The doc says:

When you run migrations, Django is working from historical versions of your models stored in the migration files.

But I can't see them there. I have data migrations with RunPython operations, but no historical models there as well. Could it be that Django generates them on the fly? How does it do it?

And while we're at it, let me confirm if I understand it correctly. Historical models are models as they were when a migration was written? Except for some limitations, like no custom methods.

like image 583
x-yuri Avatar asked Aug 31 '25 22:08

x-yuri


1 Answers

Whenever you create a model and run makemigrations. Django creates a migration file for that model which signifies the creation of such Model.

operations = [
    migrations.CreateModel(
        name='Book',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('name', models.CharField(max_length=50)),
        ],
    )
]

When you edit that model like adding a field and again run makemigrations, a new migration file is created for that change. This is the way Django stores history of that model.

operations = [
    migrations.AddField(
        model_name='book',
        name='author',
        field=models.CharField(blank=True, max_length=50, null=True),
    ),
]

The migration files are the historical models.

Now when you add some custom Python code with RunPython in migration it will be a part of the historical context for future migrations.

Migration files are set of operations that are needed to be done on database for a model. They do not have the customization of the model like save() method because this model is created from the history i.e. migration files.

like image 64
Pranav Aggarwal Avatar answered Sep 04 '25 13:09

Pranav Aggarwal