How to Create model in Django

In this Django tutorial, we will discuss How to create model in Django, How to create model fields in Django, and we will also cover the following topics.

  • Model in Django
  • Create model in Django
  • Create model form in Django
  • Using model in Django
  • Use model in view Django
  • Create model class in Django
  • Create model field in Django
  • Create object in model Django

So, before creating a model for our application, let’s first understand What is a Model in Django.

Model in Django

Django is a python based web development framework based upon 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.

Model in Django
Mapping Django model to a database table

So, in Django, we use the model to structure tables, define table fields, their default values, and many more.

Read: Python Django vs Flask

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.

Create model class in Django

To create a model in Django, we have to use the 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 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” and will be used to store employee data. And 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" (
   "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

In the example, we are creating a model in the “myApp” application. So, Django will automatically generate a table name “myApp_employees” by using models 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.

Read: How to install Django

Create model field in Django

After understanding how to create a model, next thing is to understand is model fields.

Model fields are used to represent table columns and there are many different types of fields available in Django. These different types of fields are used to decide which type of data a column should hold, for example- integer, string, date, etc. Setting up a field is just like deciding the data type of a column in the table.

Each field in a model is an instance of a Field class, and Django uses these field types to decide the column type, validation requirement, and many more things.

Now, Django offers many types of fields in the model. Here is a list of some of the most important field types.

  1. AutoField- It is an interger field field which automatically increaeses its value.
  2. BigAutoField- It is an 64 bit integer field much similar to AutoField. But the only differenece is that in this, we will get definae value from 1 to 9223372036854775807.
  3. IntegerField– It is used to hold interger values ranging from -2147483648 to 2147483647.
  4. BigIntergerField- It is also an 64 bit interger field. But it can hold integer values from -9223372036854775808 to 9223372036854775807.
  5. BinaryField- This field is used to store binary data.
  6. BooleanField– This fields can store boolean data (TRUE / FALSE). And if no default value is assigned to it then its value will be NONE.
  7. CharField- It is used to store small sized string value to large sizes string.
  8. DateField- This field is used to store data of date data type.
  9. DateTimeField- This field is used to store date and time details together.
  10. DecimalField- This field is used to store fixed-precision decimal number.
  11. EmailField– It is an CharField but it also checks wheather the value is a valid email address or not.
  12. FloatField– This field is used to store floating-point number.
  13. DurationField– This field can store periods of time.
  14. FileField- It is used for a file-upload field.
  15. ImageField This field inherits all attributes and methods from the FileField, and it also validates wheather the uploaded object is a valid image.
  16. GenericIPAddressField– It canstore IPv4 or IPv6 address in a string format.
  17. NullBooleanField- This field is just like the BooleanField, but it also allows NULL as one of the options.
  18. PositiveIntegerField- Just like an IntegerField, this field can either be positive or zero (0).
  19. SlugField- The term “slug” comes from the newspaper industry. Slugs are short labels that contain only letters, numbers, underscores, or hyphens. It is commonly used for URLs.
  20. TextField- This field is used to store large text data.

Now, there are some more fields available in Django. Each field is used to store a specific type of data.

Read: Difference between app and project in Django

Using models 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 file of our project. So, open the 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.

Using models in Django
Defining the app in the file

In the example, we have defined an app named myApp in the 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 and the command is as follows.

python makemigrations

This command helps to create migrations based upon the changes detected in our models. After this, we need to run a migrate command, and the command is as follows.

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

migrating model in Django
Output of migrations

So, with this, our model is ready to use in our project.

Read Python Django get

Create object in model Django

Till now, we have successfully created a model in Django and added the app in the 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 the 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 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.

The screenshot of the whole approach is given below.

Create object in model Django

Read: Python Django get admin password

Use model in view Django

In this section, we will learn how to access and use the model in a 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 to 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 use it for some operation. For this implementation, consider the following code.


This code will fetch all the records in the model and can easily iterate through this to get records. Let’s take an example.

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.

Create model form in Django

If we are using Django for some data-driven application, we must have to create some forms to accepts some data. Now, Django provides an efficient value to use model for creating forms. Additionally, we don’t need to use HTML for this implementation.

So, in this section, we will discuss how we can use models in Django to create a form.

In Django, we use ModelForm class that directly converts a model to a Django form. Let’s understand the implementation by executing a small example. For this, first, we will create a simple model.

from django.db import models

class Students(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    age = models.IntegerField()

In the above example, we have created a simple students model with 3 fields. These 3 fields are first_name, last_name, age respectively. Now, we will use this student’s model to generate a form.

Next, under your application directory create a file and add the following code to it.

from django import forms  
from myApp.models import Students 
class StuForm(forms.ModelForm):  
    class Meta:  
        model = Students  
        fields = "__all__"  

By using the above code, we have created a subclass of ModelForm class with the name “StuForm“. This subclass will use all the Students models fields and create a form for it.

Next, we need to create a view that will load this StuForm class from the file. For this, we will add the following code in the file of the application.

from django.shortcuts import render
from myApp.forms import StuForm

def index(request):
    stu = StuForm()  
    return render(request,"index.html",{'form':stu})  

In the above code, we have created a function-based view named index. And in the index view, we have created an object of StuForm class and then, we are sending it to the index.html page.

Next, we will add the following code to the index.html file.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Django Form</title>
    <form method="post">
        {% csrf_token %}
        <button type="submit">Save</button>

In this HTML page, we have defined a form tag, and within the form tag first, we have added a CSRF token. After this, we are using the form object to render the form.

Now, if we run the development server and open the URL for index view. We will get the following form as a result.

Create model form in Django
Django Form

You may also like reading our latest articles.

So, in this tutorial, we have discussed How to create model in Django, How to create model fields in Django, and we have also covered the following topics.

  • Model in Django
  • Create model in Django
  • Create model form in Django
  • Using model in Django
  • Use model in view Django
  • Create model class in Django
  • Create model field in Django
  • Create object in model Django