Django Models in Action

Django Models in Action

ยท

7 min read

Hey there, hope you are doing great 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 Fields

  • Add data to the created fields 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.

DRWwN1tBu.png

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 that 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 gets saved in the database table While post_save means that we are to specify what the system should do immediately after 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

Screenshot (8).png

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 for model definitions and create the table with the name "students" as specified above.

How.png

  • Go to the terminal and navigate to the directory that has our project's manage.py file in it as shown below

  • Input the following line of code to tell Django to look for model definitions and check for any changes which is needed to be created in the database and thus it creates a 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

Screenshot (94).png

  • Now is the time to create the table in the database. Input the code below in the terminal
python manage.py migrate

Screenshot (85).png

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

Screenshot (86).png

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

#Add first student to the database
student1 = students(name = 'Aremu Azeez', city = 'Ibadan', level = '300', date_admitted = '2015-05-10', active = True, reg_no = 'EEG/2014/037')
student1.save()

#Add second student to the database
student2 = students.objects.create(name = 'Bakere Paul', city = 'Lagos', level = '200', date_admitted = '2021-10-20', active = True, reg_no = 'EEG/2020/002')

#Add third student to the database
student3 = students(name = 'Soludo Micheal', city = 'Port-Harcourt', level = '200', date_admitted = '2003-10-20', active = False, reg_no = 'EEG/2004/112')
student3.save()

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 = student_list[0]
student1_name = student1.name
student1_city = sstudent1.city
student1_level = student1.level
student1_date_admitted = student1.date_admitted
student1_active = student1.active
student1_reg_no = student1.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 update any of the records in the database that 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

#Fetch the record to delete first
student = students.objects.get(name = 'Soludo Micheal', reg_no = 'EEG/2014/037')
student.delete()

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.

Firstly, Register the model in the admin.py file in the application folder by putting the lines of code below in the admin.py file

#import the students table from the 
from .models import students

#Add the table to the admin dashboard
admin.site.register(students)

Secondly, start the server and go to the address 127.0.0.1:8000/admin in your browser you should see the page below

Screenshot (87).png

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 by pressing "CTR + c" and input the code below to create a superuser

# createsuperuser
python manage.py createsuperuser

The above will ask for a 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, go to the address 27.0.0.1:8000/admin and supply the required information.

Screenshot (89).png

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? 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.

Screenshot (91).png

Screenshot (95).png

You can click on any of the student data to change any field detail.

Screenshot (91).png

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 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.

ย