[PYTHON] Rename table columns in Django3

How to rename table columns in Django3

Change the pub_data of the Question model of the polls app to pub_date.

environment

manner

Create an empty migration file

Create an empty migration file on the command line by referring to the Official Document.

$ python3 manage.py makemigration --empty [app name]

Edit migration file

Then, a migration file will be created in the polls folder directly under the application.

migrations/0002_auto_20200128_0044.py


# Generated by Django 3.0.2 on 2020-01-28 00:44

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('[app name]', '0001_initial'),
    ]

    operations = [
    ]

Rewrite this as follows.

migrations/0002_auto_20200128_0044.py


# Generated by Django 3.0.2 on 2020-01-28 00:44

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('[app name]', '0001_initial'),
    ]

    operations = [
        migrations.RenameField(
            model_name='question', #Model name
            old_name='pub_data',   #Change before
            new_name='pub_date'    #After change
        )
    ]

If you rewrite the RenameField, you can add or delete columns and indexes in the same way. For more information, go to Official Documents.

Apply migration

Finally, run the following command on the command line to apply your changes.

$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0002_auto_20200128_0044... OK

Let's check it on the SQL side.

mysql> DESC polls_question;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int          | NO   | PRI | NULL    | auto_increment |
| question_text | varchar(200) | NO   |     | NULL    |                |
| pub_date      | datetime(6)  | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

It's strange: relaxed:

Django side fix

Modify files such as model.py.

Change before

model.py


class Question(models.Model):
  question_text = models.CharField(max_length=200)
γ€€# pub_data -> pub_date
  pub_data = models.DateTimeField('data published')

  def __str__(self):
    return self.question_text

After change

model.py


class Question(models.Model):
  question_text = models.CharField(max_length=200)
  # pub_data -> pub_date
  pub_date = models.DateTimeField('date published')

  def __str__(self):
    return self.question_text

end

Why is the function name that changes the column name RenameField instead of RenameColumn?

If anyone knows another good way, please let me know.

Recommended Posts

Rename table columns in Django3
Output table structure in Django
Models in Django
django table creation
Forms in Django
Django Python shift table
Model changes in Django
Table definition in SQLAlchemy
[Django] Rename the project
[Django] Perform Truncate Table (delete all data in the table)
Performance optimization in Django 3.xx
PHP var_dump in Django templates
Handle constants in Django templates
Implement follow functionality in Django
I made a command to generate a table comment in Django
(Note) Django in Vagrant environment
Rename an existing Django application
Swap columns in pandas dataframes
Show Django ManyToManyField in Template
reload in django shell with ipython
Implement Table Driven Test in Java
Set placeholders in input fields in Django
Dynamically add form fields in Django
Errors related to memcached in django
Implementation of login function in Django
Register your Django application in your project
Write foreign key constraints in Django
How to reflect CSS in Django
Switch the language displayed in Django 1.9
Get parameter values ​​in Django templates
The meaning of ".object" in Django
Deploy Django in 3 minutes using docker-compose
Pin factory_boy seed value in Django
GraphQL API with graphene_django in Django
Like button implementation in Django + Ajax
Get the query string (query string) in Django
Create a LINE Bot in Django
Added a function to register desired shifts in the Django shift table