Home > Mobile >  Rename a field which was Primary Key in models.py
Rename a field which was Primary Key in models.py

Time:12-31

I have a model with the following fields:

email                   = models.EmailField(verbose_name="email", max_length=60, unique=True)
    department              = models.TextField(verbose_name="department")
    username                = models.CharField(max_length=30, unique=True)
    emp_id                  = models.AutoField(primary_key=True)
    is_admin                = models.BooleanField(default=False)
    is_active               = models.BooleanField(default=True)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)
    hide_email              = models.BooleanField(default=True)
    name                    = models.TextField(verbose_name="employee name")

I want to rename "emp_id" field to "id", as you can see it is the primary key field. Can you please create a migration file for the same?

Thank you

CodePudding user response:

You modify the field to:

class MyModel(models.Model):
    # …,
    id = models.AutoField(primary_key=True, db_column='emp_id')
    # …

If you then run manage.py makemigrations, Django will ask if you renamed the fied:

Did you rename mymodel.emp_id to mymodel.id (a AutoField)? [y/N]

a question you answer with yes.

This will still use the emp_id as the database id. If you want to rename the database column as well, you can just remove the emp_id field, and Django will use the default id field as primary key instead, and you can let Django make migrations the same way.

CodePudding user response:

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('your_app_name', 'name_of_previousmigration_file'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='modelname',
            name='emp_id',
        )
    ]

CodePudding user response:

class ModelName(models.Model):
    id = models.AutoField(primary_key=True)
    # other fields

Then run python manage.py makemigrations

A message will appear which will tell you to confirm that you want to rename the field emp_id to id. Type y to confirm yes.

Then run python manage.py migrate

In you application directory you'll found migration files.

  • Related