Everything About Django - 3 (Models and Migrations)

This is the third blog of the series Everything About Django. In this article we are going to study about Models and Migrations.

What are Models?

  • Models are the database tables.
  • Django uses ORM (Object Relational Mapping) for models.
  • Each model is a subclass inherited from django.db.models.Model class.
  • Every attribute in Django Model specifies a field in the database table.

What is ORM?

  • ORM means Object Relational Mapper, one of the most powerful feature of Django.
  • Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.
  • How wonderful this is, you need not type SQL and do all the db stuff.

How to create a model?

Let's take an example to see how a model is made.

from django.db import models
class Student(models.Model):
    name = models.CharField(max_length=100)
    roll = models.IntegerField()
    address = models.CharField(max_length=200)

This way I have created a table Student with the following attributes : name - Char, roll - Integer, address - Char.
In SQL we do this by :

CREATE TABLE Student
(
roll int,
name varchar(100),
address varchar(200)
);

So you see how easy and pythonic this is with Django.

What is a migration?

  • Once we have defined a model, it's just a python code not yet reflected in our database, no table is created so far, until we migrate this to our database.
  • Once our models is defined, we need to run python manage.py makemigrations. See the example bro. makemigrations
  • Here core is the app in which my models is defined. It creates a folder in my app migrations. migrations
  • With every makemigrations, a file is created like 0001_initial.py which contains the information about our reflected changes in the database, which looks like this. 0001_initial.py This is a internal file created by django to reflect changes in the db.
  • Once we have made migrations, we need to actually reflect them in the database to create and modify the table. For this run, python manage.py migrate. This command will run the latest migrations made and reflect their changes.

I will create an article on tips while creating a model, where I will define all the attributes, functions one should define in a model.

THANK YOU

You can find me on : Priyanshu Panwar | LinkedIn

Please feel free to comment for any help or topic I should write an article on.

35