Site icon i2tutorials

Django Models

DJANGO MODELS

Before you go through this tutorial, I suggest you to go through some Database Query language (SQL) knowledge and Oops concepts in python.

In this tutorial, we will understand 

  1. What is the Model in Django? 
  2. How to use the Model in Django? 

What is the Model in Django? 

Model in Django is a python class that contains associated fields, behaviors that represents the information about your data. 

Every model that you create is a Python class which is a subclass of django.db.models.Model

Using this created model you can create and access respective tables in the database that we will discuss later. 

First, let us understand how a model looks like from below code snippet. 

from django.db import models

class Courses(models.Model):
    course_name = models.CharField(max_length=30)
    course_fees = models.IntegerField()

From the above example, 

course_name, course_fees are the attributes of the model and also column names of the table.

The above code would be converted into a database table creation query as below: 

CREATE TABLE lms_courses (
    "id" serial NOT NULL PRIMARY KEY,
    "course_name" varchar(30) NOT NULL,
    "course_fees" Integer NOT NULL
);

Maybe you might have surprised in understanding the table name as how it got created as lms_courses. 

lms is the application name we create using the command 

manage.py startapp lms

Courses in the model class name combined with application name lms and created the database table name as lms_courses.

Also, I request you go through the Django Fields and Field types to build the Django models more flexible.

How to use the Model in Django? 

You need to inform the Django that you want to use the model which you created. Follow the simple steps below to do so. 

1. Get the app/module name in which your “models.py” exists.

2. Open the Settings.py file 

3. You will find the setting INSTALLED_APPS in which you add the module name.

In our example, we have an app called ‘lms’ (which is created by using “manage.py startapp lms”). that’s the module location where your models.py exists like “lms.models.py”. 

Example:

INSTALLED_APPS = [
    #...
    'lms',
    #...
]

Once you add like above, you need to run the commands.

(I will discuss the below commands in migrations article)

manage.py makemigrations 
manage.py migrate
Exit mobile version