Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename a field which was Primary Key in models.py

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading