Baby talk about Django modals

Akash N O
2 min readJul 5, 2021

Why do we need Models

Before getting into models let’s talk about why we need models. We know that we need a place to store our website data(Dynamic data). For example when a user is registering into our website with his username, email, and password we need a place to store that information. That’s where the database comes into action. And those databases contain different tables to hold data.the image below shows a database with some tables.

database example

when we start a project in Django, we will be given a database without any tables. Now it’s our job to create necessary tables into the database as per our project requirements. For creating and accessing a table in a database people generally uses SQL commands like CEATE_TABLE(blah blah) and SELECT FROM (blah blah blah).but what we want is a method to manage tables with in our language(here python).

This is where ORM(object relational mapping) comes.It is just a concept where we can write a CLASS and later convert it to a table in the database.so the class you just created to create a table is called as a Model. Now lets see the structure of a model

modal_class

The class contains the meta data of the table that we want to create. The class name is the table name(“User”) and the class variables are the fields in the table(‘name’,’age’,’number’)

but just defining a model inside models.py doesn’t magically create a table .to convert that class into an actual table , we need to run a few commands

migration commands

py manage.py makemigrations command prepare your model for migrating to the database by creating the equivalent SQL commands. py manage.py migrate commands executes the migrations(SQL commands) to the database. Now a table is created in the database.

table created in database

--

--