Table of contents
1.
Introduction
2.
Understanding Models
2.1.
Features of Django Model
3.
Using Django Models
3.1.
Creating a Model
3.2.
Rendering a Model in Django
4.
CRUD Operations in Django
4.1.
Adding Objects
4.2.
Retrieving Objects
4.3.
Modifying the Objects
4.4.
Deleting the Objects
4.5.
Validation on Fields in models
5.
Django Model Fields
5.1.
Relationship Fields
5.2.
Field Options
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Mar 27, 2024

Django Models

Author Naman Kukreja
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We will mainly focus on models in Django, how they are used to store data in the database, add entries, delete them, edit them, and much more in this blog.

Models are the feature that gives an edge over SQL for performing operations in the database easily. So without wasting time, let's get started with our blog.

Understanding Models

Django Model is an inbuilt feature in Django that is used to create tables in the database, and generally, a model in Django is a class used to store essential methods and fields.

Django creates an SQLite database for our project by default. Django officially supports four other popular relational databases in addition to SQLite: PostgreSQL, MySQL, MariaDB, and Oracle.

Sometimes SQL can be very complex as it involves lots of queries for storing data in tables, but models made it easy for Django. Each model maps to a single table in the database.

Features of Django Model

  • Each model in Django is a python class which is a subclass of django.db.models.Model 
  • Each field/attribute of the model represents a field in the database.
  • We can perform CRUD(create,retrieve,utilize,delete) operations on the database table.
     
from Django.db import models
 
# Create your models here.
class NinjaModel(models.Model):
    title = models.CharField(max_length = 200)
    description = models.TextField()

Using Django Models

One must need to have a project and an app working on it. After that, one can create models in app/models.py.

Creating a Model

We are creating a model in ninja/models.py. First of all, we’ll create a class(similar to tables) and inherit the models.

# importing the function from built-in library
from django.db import models

# here declaring  a new model with a name "NinjaModel"
class NinjaModel(models.Model):
        # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
    last_modified = models.DateTimeField(auto_now_add = True)
    img = models.ImageField(upload_to = "images/")

        # renames the instances of the model
        # with their title name
    def __str__(self):
        return self.title

 

No matter what we are doing with the model, whether we create it, delete it, or edit it. We have to run two commands for generating and executing SQL commands. 

Python manage.py makemigrations

 

When the above command runs, the model is created as a table.

Python manage.py migrate

 

When the above command runs, the table is created in the database.

Rendering a Model in Django

In order to render a model in Django, we need to go to admin.py in the ninja app and change the code with this.

from django.contrib import admin
  
# Register your models here.
from .models import NinjaModel
  
admin.site.register(NinjaModel)

CRUD Operations in Django

With the help of an API named ORM, a database-abstraction API, We can perform certain operations like delete, add, modify query objects.

Adding Objects

In order to create/add an object and save it in the database, we must write the following command.

>>> a = NinjaModel(
        title = CodingNinja,  
        description = "A description here",
        img = ninja/abc.png"
        )
>>> a.save()

Retrieving Objects

For retrieving all the objects, We need to write the following command

>>> NinjaModel.objects.all()
<QuerySet [<NinjaModel: Divide>, <NinjaModel: Abbey Road>, <NinjaModel: Revolver>]>

Modifying the Objects

To do so, we need to write the following command

>>> a = NinjaModel.objects.get(id = 3)
>>> a.title = "Pop"
>>> a.save()

Deleting the Objects

For deleting the object write the following command

>>> a = Album.objects.get(id = 2)
>>> a.delete()

Validation on Fields in models

There are many default validations in Django fields. Every field has a built-in validation from Django validators.

Enter the following code in models.py in the ninja app.

from django.db import models
from django.db.models import Model
# Create your models here.

class NinjaMoel(Model):
    ninja_field = models.IntegerField()

    def __str__(self):
        return self.ninja_field

Django Model Fields

The most important part of the model is the list of database fields. The tables below explain all available fields.

Relationship Fields

The relationship fields are given below.

Field Options

These are some arguments with some constraints given to each field.

Frequently Asked Questions

  1. Which of the two is easy to work, SQL or Models?
    Models are easy to work with.
     
  2. What are some features that Models provide?
    They provide us with features like add, delete, update, etc.
     
  3. How many commands do we have to run while creating a model?
    We have to run two commands whenever we are making a model.
     
  4. What do you mean by BinaryField?
    IT is a field that stores raw Binary data.

Key Takeaways

In this blog, we have learned about Django Models, their features, fields, and much more.

If you want to prepare Django for your interviews and are looking for questions to practice, Don’t worry Coding Ninja has a proper list of Questions to prepare for Django Interview.

Live masterclass