How to Rename Class in Django

Posted on

This article is actually related with the article where an application located in a Django framework-based project is changed. Read the article titled ‘How to Rename Application in Django’ in this link. The application name is not changed but the name of the class defined in a file named models.py which is representing the table in a database connected. For an example if there is a class named ‘tasks’ and it is going to be renamed as ‘Tasks’ because of the convention or standard to use a capital letter for the first letter of the class name, below is the step of the execution :

1. Rename the class name located in the file named models.py. Usually, it is located in the following location :

user@hostname:~/apps$ tree -L 2
.
├── db.sqlite3
├── manage.py
├── apps
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
└── module
    ├── admin.py
    ├── admin.pyc
    ├── apps.py
    ├── apps.pyc
    ├── __init__.py
    ├── __init__.pyc
    ├── migrations
    ├── models.py
    ├── models.pyc
    ├── static
    ├── templates
    ├── tests.py
    ├── urls.py
    ├── urls.pyc
    ├── views.py
    └── views.pyc
user@hostname:~/apps

2. The content of the file named ‘models.py’ is shown as follows :

from __future__ import unicode_literals
from datetime import datetime
from django.db import models
# Create your models here.
class tasks(models.Model):
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_at = models.DateTimeField(default=datetime.now)
    def __str__(self):
        return self.title

3. Change the name of the class as follows :

from __future__ import unicode_literals
from datetime import datetime
from django.db import models
# Create your models here.
class Tasks(models.Model):
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_at = models.DateTimeField(default=datetime.now)
    def __str__(self):
        return self.title

4. Execute the following command after editing the file :

user@hostname:~/apps$ python manage.py makemigrations
Did you rename the apps.tasks model to Tasks? [y/N] y
Migrations for 'apps':
  0002_auto_20180217_1609.py:
    - Rename model tasks to Tasks
user@hostname:~/apps$ 

The next step is to implement the migration script created by executing the above command :

user@hostname:~/apps$ python manage.py migrate
Operations to perform:
  Apply all migrations: account, network, service, sessions, admin, sites, auth, server, contenttypes, socialaccount
Running migrations:
  Rendering model states... DONE
  Applying apps.0002_auto_20180217_1609... OK
user@hostname:~/apps$

5. After the migrations successfully carried out, don’t forget to check the table name again.

Leave a Reply