Django Tutorial · Django Tutorial

Django Update Model

Learn all about Django Update Model in this comprehensive tutorial.

5 min read intermediate
  • To add a field to a table after it is created, open the models.
  • We can insert data to the two new fields with the same approach as we did in the Update Data chapter:

Add Fields in the Model

To add a field to a table after it is created, open the models.py file, and make your changes:

As you can see, we want to add phone and joined_date to our Member Model.

This is a change in the Model's structure, and therefore we have to make a migration to tell Django that it has to update the database:

python
Note: Note: Make sure you are back in the virtual environment before running the command.

The command above will result in a prompt, because we try to add fields that are not allowed to be null, to a table that already contains records.

As you can see, Django asks if we want to provide the fields with a specific value, or if we want to stop the migration and fix it in the model:

python

I will select option 2, and open the models.py file again and allow NULL values for the two new fields:

And make the migration once again:

python

Which will result in this:

python

Run the migrate command:

python

Which will result in this output:

python

Insert Data

We can insert data to the two new fields with the same approach as we did in the Update Data chapter:

First we enter the Python Shell:

python

Now we are in the shell, the result should be something like this:

python

At the bottom, after the three >>> write the following (and hit [enter] for each line):

python

This will insert a phone number and a date in the Member Model, at least for the first record, the four remaining records will for now be left empty. We will deal with them later in the tutorial.

Execute this command to see if the Member table got updated:

python

The result should look like this:

python

Module quiz

2 questions
1

Which of the following is true about Django Update Model?

2

What is the most common pitfall when working with Django Update Model?

Answer all questions to submit.