Django Update Model
Learn all about Django Update Model in this comprehensive tutorial.
- •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:
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:
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:
Which will result in this:
Run the migrate command:
Which will result in this output:
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:
Now we are in the shell, the result should be something like this:
At the bottom, after the three >>> write the following (and hit [enter] for each line):
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:
The result should look like this:
Module quiz
2 questionsWhich of the following is true about Django Update Model?
What is the most common pitfall when working with Django Update Model?
Answer all questions to submit.