Home > Back-end >  Renaming Django primary key
Renaming Django primary key

Time:10-04

I am trying to rename the primary key field of a Django model, but I get django.db.utils.ProgrammingError: column "new_name" of relation "my_app_mymodel" does not exist.

The model is something like this:

from django.db import models as django_db_models

class MyModel(django_db_models.Model):
    old_name = django_db_fields.BigAutoField(
                   null=False,
                   primary_key=True,
                   auto_created=True,
                   unique=True,
               )

And the migrations is:

# Generated by Django 3.2.6 on 2022-10-03 15:33

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('my_app', '0007_previous_migration'),
    ]

    operations = [
        migrations.RenameField(
            model_name='mymodel',
            old_name='old_name',
            new_name='new_name',
        ),
    ]

Not sure what am I doing wrong. Any ideas?

P.S: I don't know if this is related but there are foreign keys from other tables to this one.

CodePudding user response:

1 - rename the field in the model :

from django.db import models as django_db_models
class MyModel(django_db_models.Model):
    new_name = django_db_fields.BigAutoField(
                   null=False,
                   primary_key=True,
                   auto_created=True,
                   unique=True,
               )

2- run python manage.py makemigrations (it will just create new migrations based on that change)

3- then Change the field’s name :

operations = [
        migrations.RenameField(
            model_name='mymodel',
            old_name='old_name',
            new_name='new_name',
        ),

4 - run python manage.py migrate (it will rename the field and keep your data )

CodePudding user response:

django.db.utils.ProgrammingError: column "new_name" of relation >"my_app_mymodel" does not exist

When you see the above error message, It means that you've not done the migration yet and you've only created the related migration file for this change. However, you can do this with the following command and then this problem will be solved and you will no longer see this error:

python manage.py migrate
  • Related