In this Django tutorial, we will discuss How to create model in Django, In addition, we will learn about models in Django, and how to create a model class in Django. Moreover, we will explore how to create an object in the model and the use of the model in view using the Django web framework.
Model in Django
Django is a Python-based web development framework based on MVT architecture. And the “M” in the MVT represents the Model.
A Model in Django is a Python object, and it is used to access and manage data for your application. Each model in Django maps to a database table.
Generally, we write multiple SQL queries to create a SQL database and then create tables and their fields. But Django simplifies this task by organizing tables using Model.
So after selecting the database, we only need to create models, and Django will automatically communicate with the database to implement the task.
Here is an image below which represents how the Django model maps to a database table.
So, in Django, we use the model to structure tables, define table fields, their default values, and many more.
How to Create a Model in Django
After understanding the model, it’s time to discuss how to create a model in Django. But before moving forward, one should have a project and an application ready. For this, you can also refer to the following article – How to setup Django project.
How to create a model in Django Project Setup
Before creating the model, first set the project environment, by following the below steps:
Open your terminal or command prompt and type the below command to create an environment named ‘env’.
python -m venv env
Then activate the environment ‘env’ using the below code.
env\Scripts\activate
Install the latest version of Django.
pip install django
Create a Django project ‘myProject’ using the below command.
django-admin startproject myProject
Change the current directory to the ‘myProject’ directory.
cd myProject
Create a Django app named ‘myApp’ using the below code.
python manage.py startapp myApp
After this, you can open the project in your preferred IDE such as Visual Studio Code or you can with current command prompt or terminal.
Create a model class in Django
To create a model in Django, we have to use the model.py file that will be available in your app’s directory.
Now, each model in Django is a Python class which will be a subclass of the django.db.models.Model class. And each attribute of a class represents a field.
So, here is a general syntax that we can use in the models.py file to create a user model.
from django.db import models
class ModelName(models.Model):
field_name = models.Field(**options)
In the syntax, first, we have imported the models class. After this, to create a user model, we have to define a subclass of “models.Model“.
In the syntax, we have to define the name of our model in place of ModelName. Next, to create the fields, we have to use the models class as shown in the syntax.
Let’s understand this by taking an example and for this, consider the code given below.
from django.db import models
class Employees(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
Dept_name = models.CharField(max_length=20)
joining_date = models.DateField()
salary = models.IntegerField()
In the above example, we have created a user model with the name “Employees” which will be used to store employee data. In the model, we have defined 5 fields as a class attribute, and each attribute will map to a database column.
Now, this Employees model will automatically create a table equivalent to this.
CREATE TABLE "myApp_employees" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL,
"Dept_name" varchar(20) NOT NULL,
"joining_date" date NOT NULL,
"salary" integer NOT NULL
);
COMMIT;
In the example, we are creating a model in the “myApp” application. So, Django will automatically generate a table name “myApp_employees” by using model metadata.
Additionally, an id field will also be added to the table. This id is a NOT NULL, AUTOINCREMENT, PRIMARY KEY field.
So, with this, we have understood How we can create a model class in Django and what happens when we create a model. Next, let’s understand How we can use models in Django.
Make Migration in Django
After successfully creating a model class, let’s understand how to use a model in Django.
First, we need to tell the Django server that we want to use a model. For this, first, we need to use the settings.py file of the Django project ‘myProject’. So, open the settings.py file and give the name of your app having a model in the INSTALLED_APPS section.
Here is an example of how we should add the apps in the settings file.
In the example, we have defined an app named myApp in the settings.py file of the project.
Next, we need to run the migrations so the table can be created. Django uses migrations to propagate changes to your models (adding a field, deleting a model, etc.) to your database schema.
First, run the makemigrations command as shown below.
python manage.py makemigrations
This command helps to create migrations based on the changes detected in our models. After this, we need to run a migrate command, and the command is as follows.
python manage.py migrate
This migrate command is responsible for applying the changes made in the model to the database. Here is the screenshot related to the migrations.
So, with this, our model is ready to use in our project.
How to create an object in model Django
Till now, we have successfully created a model in Django and added the app in the settings.py file. So, now we can use the model for our project.
Now, Django uses the model class to represent database tables and objects as a record in the table. So, in this section, we will learn how to create objects of a user model and use them to save data in the table.
For this demonstration, we will be using a Python shell, and to open the shell, we have run the following command in our project directory.
python manage.py shell
Now, an interactive console will be activated, and we will execute all the steps in the console.
After this, our first step is to import the required model from our application and we can use the following syntax for this task.
from app_name.models import model_name
Here is an example of how we can import the “Employees” model from our myApp application.
from myApp.models import Employees
Now to create an object, we have to pass the values of the fields as an argument to the model class. A simple example of the Employees model is given below.
emp = Employees(first_name='Steve', last_name='Rogers', Dept_name='Technical', joining_date='2020-08-15', salary=25000)
In the example, we have created an object named “emp” and it is used to store 5 fields in the Employees table. Next, to store this record in the table, we have to use the save() method. In Django, the save() method is used to implement the SQL insert. Here is how we should use the save() method.
emp.save()
The screenshot of the whole approach is given below.
Read: Python Django get admin password
How to use the model in view of Django
In this section, we will learn how to access and use the model in view of a Django application.
Now, as discussed in the previous section, the first step is to import the required model into the view. For this, simply use the import statement. By importing the model, we can easily access the model in the view.
from app.models import ModelName
Now the usability of the model in a view totally depends upon the requirement. If we want to insert records in the table then, we have to create an object and insert it using the save() method.
Another requirement can be accessing the model data and then using it for some operation. For this implementation, consider the following code.
ModelName.objects.all()
Let’s take an example where we will create a view named ‘index’ and this view retrieves all the employees from the database as objects.
To create a view open the views.py file of your Django app ‘myApp’. Then the below code will fetch all the records in the model and can easily iterate through this to get records.
from django.http import HttpResponse
from myApp.models import Employees
def index(request):
emp_list = Employees.objects.all().count()
return HttpResponse(emp_list)
In the example, we simply created an index view that will return the total count of the records available in the Employees model.
Conclusion
In conclusion, we have learned to create a model in Django by defining the Python class models.py with how to specify different fields in the model.
In addition, we have learned to make migrations of the Django model which is one of the most important steps for updating the database schema. With this, we explore integrating the model into Django views.
Moreover, we will move on and learn the steps to create the object in the model using the Django web framework.
You may also like reading our latest articles.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.