How To Add New Model Field To Exist Django Model

When you develop Django app, you always need to change the model fields. But how to make the changes take effect ( add / remove table column to / from backend database table ). To a beginner, this question may be confused. This article will tell you how to do it.

1. Change Django Model Field Steps.

  1. Change model class field in Django application models.py file. Below example add a new field user_desc = models.CharField(max_length=100, default=”), and remove fieldĀ emp_onboard_date = models.DateTimeField(auto_now=True).
    class Employee(models.Model):
        ......
        #emp_onboard_date = models.DateTimeField(auto_now=True)
    
        user_desc = models.CharField(max_length=100, default='')
        ......
  2. You had better specify a default value for the new field, otherwise you may encounter below error message when you make migrations.
    $ python3 manage.py makemigrations dept_emp
    
    You are trying to add a non-nullable field 'sex' to employee without a default; we can't do that (the database needs something to populate existing rows).
    Please select a fix:
    1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
    2) Quit, and let me add a default in models.py
    Select an option:
  3. Then goto the Django project root folder in a terminal and run makemigrations command. It will generate a new migration .py file in the application migrations folder ( dept_emp / migrations ).
    $ python3 manage.py makemigrations dept_emp
    
    Migrations for 'dept_emp':
      dept_emp/migrations/0004_auto_20190228_0617.py
        - Remove field emp_onboard_date from employee
        - Add field user_desc to employee
    
    Process finished with exit code 0

    makemigrations after model class field change

  4. Execute migrate command in terminal, then it will apply above migration .py file to the database table.
    $ python3 manage.py migrate dept_emp
    
    Operations to perform:
      Apply all migrations: dept_emp
    Running migrations:
      Applying dept_emp.0004_auto_20190228_0617... OK
    
    Process finished with exit code 0
  5. Then open the Django project sqlite3.db file to see that the database table has been changed accordingly.
READ :   Python String Function Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.