Model Inheritance in Django 

  • By Deepali Shinkar
  • December 8, 2023
  • Python
Model Inheritance in Django 

Model Inheritance in Django 

Django is a high-level, open-source web framework written in Python that follows the Model-View-Controller (MVC) architectural pattern. It is designed to facilitate the rapid development of robust, scalable, and maintainable web applications. Django encourages the use of reusable code, follows the “Don’t  Repeat Yourself” (DRY) principle, and aims to make web development as straightforward as possible. In this blog, I am explaining the Model Inheritance in Django. At SevenMentor, we offer a comprehensive Django course designed to equip you with the skills needed to build robust and scalable web applications. 

 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

Key Features of Django: 

Security 

ADMIN  

INTERFACE

Template  Engine 

Features of  Django 

MVC 

Middleware U

  1. Batteries-Included Philosophy Django follows a “batteries included” philosophy, providing a comprehensive set of features and tools which includes an ORM (Object-Relational Mapping) system, an admin interface, authentication, URL routing, form handling, and more.

 

  1. ORM (Object-Relational Mapping): Django’s ORM allows developers to interact with databases using Python objects

  2. Admin Interface: Django provides an automatic admin interface for managing database records. Developers can leverage this feature to perform CRUD (Create, Read, Update, Delete) operations on their models without having to create a custom admin panel. 

 

  1. MVC Architecture: Django follows the Model-View-Controller  (MVC) architectural pattern, although in Django, it’s often referred to as the Model-View-Template (MVT). Models represent the data structure, Views handle the presentation logic, and Templates manage the UI.

    5. URL Routing: Django uses a clean and flexible URL routing system.  URLs are mapped to views, allowing developers to define how different parts of the application respond to specific requests. 

 

  1. Middleware: Django middleware allows developers to process requests globally before they reach the view and responses globally before they are sent to the client. This provides a way to add functionality such as authentication, security features, and more. 
  2. Security Features: Django has security features built into its core,  including protection against common web vulnerabilities like SQL  injection, cross-site scripting (XSS), and cross-site request forgery  (CSRF).
  3. Template Engine: Django comes with its template engine that allows developers to define the structure of HTML pages using a  template language that includes logic, variables, and filters. 

In Django, a model is a Python class that defines the structure of a database table. Models are a key component of Django’s Object-Relational Mapping  (ORM) system, which enables you to interact with your database using high-level Python objects rather than raw SQL queries. Models represent the data structure of your application, allowing you to define fields, relationships, and behaviors for your database entities. 

In short , model means 

A Django model is a table in your database. 

A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. 

In short, Django Models is the SQL Database one uses with Django.  The basics of a model include – 

Each model is a Python class that subclasses django.db.models.Model.

Each attribute of the model represents a database field. With all of this, Django gives you an automatically generated database-access API Django provides a built-in database by default which is a SQLite database. 

We can use another database like MySQL, Oracle SQL, etc. Create own model class 

models.py file which is inside the application folder, is required to create our own model class. 

Our own model class will inherit Python’s Model Class. 

 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

Syntax of Model Inheritance in Django: 

class ClassName(models.Model): 

 field_name=models.FieldType(arg, options)Example of model class : 

Rules for field : 

  1. Field Name is instantiated as a class attribute and represents a particular table’s Column name. 
  2. Field Type is also known as Data Type. 
  3. A field name cannot be a Python reserved word, because that would result in a Python syntax error. 
  4. A field name cannot contain more than one underscore in a row, due to the way Django’s query lookup syntax works.  
  5. A field name cannot end with an underscore. 

Once you have defined your models, you need to tell Django you’re going to use those models. 

  • Open settings.py file  
  • Write the app name which contains the models.py file in INSTALLED_APPS =  [ ] 
  • Open Terminal  
  • Run python manage.py makemigrations
  • Run python manage.py migrate 

makemigrations is used to convert model classes into SQL statements. This will also create a file that will contain SQL statements. This file is located in the Application’s migrations folder. 

Syntax:- python manage.py makemigrations 

migrate is used to execute SQL statements generated by makemigrations.  This command will execute All Applications (including built-in applications)  SQL Statements if available. After the execution of SQL statements, the table will be created. 

Syntax:- python manage.py migrate 

Note – If you make any change in your own model class you  are required to run makemigrations and migrate commands only then you will get those changes in your application. 

 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

Using Models in Views and Templates:

Once your model is defined and migrations are applied, you can use it in your views and templates to interact with the database. Django’s ORM will handle the translation between Python objects and database records. 

Let’s dive into model inheritance in Django with an example. Three types of  model inheritance: 

Abstract base classes: For the parent class to hold information we don’t have to type it out for each child model. 

Multi-table Inheritance: For subclassing an existing model and letting each model have its own database. 

Proxy models: Modifying the model’s Python-level behavior without having to change its fields. 

1. Abstract Base Class : 

Consider a scenario where you want multiple models to have common timestamp fields. You can use an abstract base class to achieve this:

In this example, TimestampedModel serves as an abstract base class with timestamp fields. The BlogPost model then inherits from TimestampedModel, gaining the created_at and updated_at fields. 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

2. Multi-table Inheritance: 

Imagine a situation where you have a general Person model, and you want  to create more specific models like Employee and Customer with additional  fields:

Here, Employee and Customer inherit from the Person model, creating separate tables for each with their specific fields. 

 

For Free, Demo classes Call: 02071171500

Registration Link: Python Training in Pune!

 

3. Proxy Models: 

Suppose you have a Book model, and you want to create a special version of it for administrative purposes without altering the existing table. You can  use a proxy model:

In this case, AdminBook is a proxy model that shares the same database table as Book but can have additional methods or behavior. 

Do Watch our Python Video: Click Here

 

Conclusion: 

Model inheritance in Django allows you to design your database models in a  flexible and reusable way. Abstract base classes, multi-table inheritance, and proxy models offer different strategies for structuring your models based on the requirements of your application. By leveraging these inheritance types,  you can create a clean and organized database schema that aligns with the logic and structure of your project.

Author:-
Deepali Shinkar
Call the Trainer and Book your free demo Class For Django

Call now!!! | SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*