Django Models in Action
Hey there, how are you doing today? Today we will look into Django models in action after we have discussed different fields of models we can use in the last article Django Models. In this article, we will
Create a Database table with Django Field
Add data to the created field through Django in-built API and Admin panel
Update created data in the table
Delete a data entry in the field
I will assume you know how to create a Django project and application, if not, check out my article Create Django Application. Now let us dive in straight away 🚀🚀🚀.
Create Database Table
Database Table is the rows and columns where we store our records for instance the record below which has information about students showing the name, surname, city, and grade.
To create a table like this in Django, We write database statements known as models in the models.py file as commonly done. To create an effective model you should highlight some basic needs somewhere (a sheet of paper maybe).
The columns you will need
The data type to use for each column
Validation methods to use for each column
The length of the fields which requires max_length to be specified
Maybe pre_save or post_save actions to perform
pre_save means that we are to specify what the system should do before the data got saved in the database table While post_save means that we are to specify what the system should do immediately the data is saved in the database table.
For our school database, we will need
Six columns ( Name, City, Level, Date_Admitted, Active and Reg_No)
Data types to use are (Name-string, City-string, Date_Admitted-Date, Active-Boolean, and Reg_No-string). I believe you still remember the corresponding field we are to use for each column specified above, if not kindly check it out here Django Models
Name Field( max_length = 250), City Field( max_length = 120) and Reg_No field (max_length = 15 )
pre_save action can be to check if the student is not active, the system should make the student active
Now let's go to our code editor ( i will be using visual studio code) and open our models.py file in our application folder as shown below
Put the following lines of code in the opened models.py file
from django.db import models from django.utils import timezone class students(models.Model): name = models.CharField(max_length = 250) city = models.CharField(max_length = 120) level = models.PositiveIntegerField() date_admitted = models.DateField(default=timezone.now)#timezone.now will automatically fill the datefield for us as today's date if we left it with no data active = models.BooleanField() reg_no = models.CharField(max_length = 15) # The method defined below will let us see the students name when any student instance is called def __str__(self): return self.name
Django does not know what we have done, so we need to tell Django to look into the models.py file and create the table with the name students as specified above.
- Go to the terminal and navigate to the directory which has our project's manage.py file in it as shown below
- Input the following line of code to tell Django to look into the models.py file for any changes which is needed to be created in the database and thus it created migrations file that contains these definitions
python manage.py makemigrations #If you check your application folder you should have a migration file now created for you as shown below
- Now is the time to create the table in the database. Input the code below in the terminal
python manage.py migrate
Well done so far, Now let's get the students registered using both the inbuilt API and the admin dashboard
CRUD Django database from API
We can perform four major tasks with any table created successfully, These tasks are CREATE, READ, UPDATE and DELETE known as ( CRUD ACTION). To get access to the API you just have to input the command below in the terminal in the directory with our project's manage.py file and you should have access to the API as shown below.
python manage.py shell
Before we can add any data to the database we will need to import the table from the models.py file with the code below put in the API
from first_model.models import students
Now add the students to the database as shown below
name = 'Aremu Azeez', city = 'Ibadan', level = '300', date_admitted = '2015-05-10', active = True, reg_no = 'EEG/2014/037') student1.save() student2 = students(name = 'Bakere Paul', city = 'Lagos', level = '200', date_admitted = '2021-10-20', active = True, reg_no = 'EEG/2020/002') student2.save() student3 = students(name = 'Soludo Micheal', city = 'Port-Harcourt', level = '200', date_admitted = '2003-10-20', active = False, reg_no = 'EEG/2004/112') student3.save()student1 = students(
We have created data to the database, Now let's read the data from the database by doing the following
#Get all the students at once student_list = students.objects.all() #Get the first student details from the list student1_name = student_list.name student1_city = student_list.city student1_level = student_list.level student1_date_admitted = student_list.date_admitted student1_active = student_list.active student1_reg_no = student_list.reg_no #Get student by any of his / her info which are name, city, level, date_admitted, active, reg_no, or pk(id) student1 = students.objects.get(reg_no = 'EEG/2014/037') #Get the student details student1_name = student1.name student1_city = student1.city student1_level = student1.level student1_date_admitted = student1.date_admitted student1_active = student1.active student1_reg_no = student1.reg_no
Now let's now update any of the records in the database which must have been fetched first
#Fetch the record to update first student = students.objects.get(reg_no = 'EEG/2014/037') #see the name and level of the student student_name = student.name student_level = student.level #change the name of the student student.name = 'Ajibola Akeem' #change the student's level student.level = 400 #save the changes student.save()
So we have a student detail we need to get rid of in the database? We can delete that in the manner below
get(name = 'Soludo Micheal', reg_no = 'EEG/2014/037') student.delete()student = students.objects.
CRUD from the Django Admin Dashboard
So far so good we have added data from the API but we can also do the same from the admin dashboard that came with Django.
#import the students table from the from .models import students #Add the table to the admin dashboard admin.site.register(students)
Second, start the server and go to the address 127.0.0.1:8000/admin in your browser and you should see the page below
You just asked what the username and password are right? We have not created that. Now go back to the terminal and stop the server and input the code below to create a superuser
# createsuperuser python manage.py createsuperuser
The above will ask for username, email, and password which is expected of you to be supplied and we will now use the username and password to login into the admin dashboard.
Now start the server again and go to the address 22.214.171.124:8000/admin and supplied the required information.
If you check our table name from above you will see it has two s instead of one. Django has been configured to add s to the name of the table but we don't want this right and so what should we do?
Go back to the models.py file and replace it with the lines of code below and then save and refresh the browser to see the changes
from django.db import models from django.utils import timezone class students(models.Model): name = models.CharField(max_length=250) city = models.CharField(max_length=120) level = models.PositiveIntegerField() date_admitted = models.DateField(default=timezone.now)#timezone.now will automatically fill the datefield for us as today's date if we left it with no data active = models.BooleanField() reg_no = models.CharField(max_length = 15) # The method defined below will let us see the students name when any student instance is called def __str__(self): return self.name # New lines class Meta: verbose_name_plural = 'students'
Third, Click on the table name and you should see the students' data we added from the API, Locate and click the ADD STUDENTS button in the top right-hand corner of the page and you will be taken to the page like below. Fill in the required information and click save.
You can click on any of the student data to change any field detail.
That's it for now on the CRUD action in Django, I hope you now know how to CREATE, READ, UPDATE and DELETE from the database.
Kindly do check the documentation to learn more about some other query functionalities and keywords here
In the next article, we will look into presenting the data in the database to our website visitors using the views and template system.
Thank you for reading.