How to change model field names among themselves in Django?

  Kiến thức lập trình

I have created a model in my Django project. By mistake, I set the date_created and date_updated fields wrong as follows:

class Article(models.Model):
    date_created = models.DateTimeField(auto_now=True)
    date_updated = models.DateTimeField(auto_now_add=True)

I should have set date_created as auto_now_add=True, and date_updated as auto_now=True. Now, when I want to change the model names by each other as

class Article(models.Model):
    date_updated = models.DateTimeField(auto_now=True)
    date_created = models.DateTimeField(auto_now_add=True)

Django detects that I just changed the definition of the fields and creates a migration as

    operations = [
        migrations.AlterField(
            model_name='article',
            name='date_created',
            field=models.DateTimeField(auto_now_add=True),
        ),
        migrations.AlterField(
            model_name='article',
            name='date_updated',
            field=models.DateTimeField(auto_now=True),
        ),
    ]

But I actually renamed them. When I manually set the migrations as RenameField, it simply does not work because Django detects that I have not created a migration for the changes that I made.

Renaming with a different name could be solution, but I need to keep the field names. What can I do in this situation?

New contributor

Burak is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Edit the migration file with three renames:

operations = [
    migrations.RenameField(
        model_name='article',
        old_name='date_created',
        name='date_updated1',
    ),
    migrations.RenameField(
        model_name='article',
        old_name='date_updated',
        name='date_created',
    ),
    migrations.RenameField(
        model_name='article',
        old_name='date_updated1',
        name='date_updated',
    ),
]

this will thus eventually swap the two fields.

LEAVE A COMMENT