Search anything:

Models in Django

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time:30 minutes

In this article, we'll be learning about Models in Django and how the database system works in Django.

How to store information?

Let us take an example, you want to create a social networking website in Django and we need a systematic way to define and store things such as user profiles and their details, posts, and their details, messages, comments, pages, and many more things. What do you think about how Django does that? How it will store this data?

Generally, when web applications are created, they consist of a front end and a back end.

  • The front end consists of the user interface (HTML, CSS, etc)
  • The back end means the server and database where all the necessary information is stored.

In this case, we need a server where all the information could be stored and can be visible to the user when needed. Generally, Relational type of databases are popular wherein information is stored in the form of a relation (table) consisting of various attributes (in the form of columns).

Let us suppose, these are some basic components that we want to include in our site and we need Django to store the information, in that case, we use the concept of a "Model". We already know that Django uses MTV architecture where the Model is responsible for handling data logic.


On similar lines, a 'MODEL' in Django is an object stored in the database which represents a particular entity (same as we create a table in Relational Database) and it contains various attributes ( just like different columns/fields of that table). It involves the concept of Object Oriented Programming where things are defined in a modular and systematic way. For example, for our site, to model a "post" we will create an object "post" which will have properties such as caption, content, comments, etc. Further, we'll create methods to link all the models.

We'll be using SQLite database for storing all the databases. SQLite is the default database that Django uses. One can use different databases as well.

All the models that we'll be creating would be in 'models.py' file that is by default present in the Django app that we create using the command:

python manage.py startapp myapp
   ├── admin.py
   ├── apps.py
   ├── __init__.py
   ├── migrations
      └── __init__.py
   ├── models.py
   ├── tests.py
   └── views.py

models.py file

We know how to create a basic Django project. After setting it up properly we'll open our models.py file present in the app we created.

from django.db import models
from django.db.models.deletion import CASCADE
from django.core.validators import RegexValidator

We included models from django.db as all the models in Django are inherited from django.db.models.Model. Further, we'll see where CASCADE and validators are used.

Now we'll define all our objects using classes in python.

class Profile(models.Model):
    username = models.CharField(max_length = 100)
    f_name = models.CharField(max_length = 100, null=True,blank=True)
    l_name = models.CharField(max_length = 100, null=True,blank=True)
    age = models.IntegerField(default=18)
    phone_no = models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")], max_length=15, null=True, blank=True)
class Post(models.Model):
    pic=models.ImageField(upload_to = "images\\", null=True)
    caption = models.CharField(max_length = 200)
    content = models.TextField(null=True, blank=True)
    cr_date = models.DateTimeField(auto_now_add=True)
    uploaded_by = models.ForeignKey(to=Profile, on_delete=CASCADE, null=True, blank=True)
class Comments(models.Model):
    post = models.ForeignKey(to=Post, on_delete=CASCADE)
    comment = models.TextField()
    commented_by = models.ForeignKey(to=Profile, on_delete=CASCADE)
    cr_date = models.DateTimeField(auto_now_add=True)
 class Likes(models.Model):
    post = models.ForeignKey(to=Post, on_delete=CASCADE)
    liked_by = models.ForeignKey(to=Profile, on_delete=CASCADE)
    cr_date = models.DateTimeField(auto_now_add=True)


Whenever we define attributes of a particular object then we need to specify the type that field will have. ( What type of data that attribute will hold?)

  • models.CharField – this defines text with a limited number of characters, the max_length argument defines the limit, null if true means that django will store NULL value in the database and blank if true means that the field is allowed to be blank. Validators provide us with a list of different validators for the field.
  • models.TextField – this type is for long text like for typing some long message or comments.
  • models.ImageField - used for uploading image formats (Note: ImageField requires Pillow library, so, in the command prompt run the following command pip install Pillow)
  • models.DateTimeField – this type for data and time, here its used when a post or comment is created. In this, auto_now_add when true is used to record the time when the object is created. It is useful for timestamps.
  • models.IntegerField - this type is for integers. In this, default is used to set a default value beforehand.
  • models.ForeignKey – Now, a foreign key in the relational database is a field or group of fields used for linking two tables. On similar lines, this type is used for linking models. The argument 'to' specifies how it is linked and on_delete when it is CASCADE, it means that when a particular record will be deleted, all the records linked/related to it will also get deleted.

Migrations in Django

Now, migrations are a special method in Django to propagate all the changes you make to your models. That means for models to be registered to your database in Django, we need to make migrations. You'll notice that there is a folder named 'migrations', inside that folder there's an empty python file named init.py, here all the migrations will be stored in different python files.

There are two commands which are used for making migrations. Open the command prompt at the place where manage.py is present and the run the following

python manage.py makemigrations

This command makes new migrations and puts up into a separate python file. After successfully executing it, run the following command,

python manage.py migrate

It applies all the migrations to the database.

Now, your database is updated with all the new models. You can view your database by opening 'db.sqlite3' file in your directory using a suitable browser.

Time to try it out yourself.

Now that you are aware of how Django works, you can take a real-life example of your own such as a banking system or a book store, and make a database on your own using Django from scratch. It will not take much time and would be a fun task to do.

Models in Django
Share this