Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Model Three Inheritance Models

Django supports three types of model inheritance: abstract base classes, multi-table inheritance, and proxy models. In this tutorial, we will cover each of these inheritance models:

  1. Abstract base classes
  2. Multi-table inheritance
  3. Proxy models

1. Abstract base classes

An abstract base class is a model that is not meant to be instantiated on its own but is meant to be subclassed by other models. Abstract base classes do not create a database table and are used to share fields and methods among subclasses. To create an abstract base class, set the abstract attribute in the Meta class to True.

Example:

from django.db import models

class BaseModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Author(BaseModel):
    name = models.CharField(max_length=100)

class Book(BaseModel):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

In this example, BaseModel is an abstract base class that contains two common fields: created_at and updated_at. The Author and Book models inherit from BaseModel and automatically gain these fields.

2. Multi-table inheritance

Multi-table inheritance allows a model to inherit fields from another model, creating a new table in the database for each model in the inheritance chain. A OneToOneField is automatically created between the parent and child models.

Example:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

class Employee(Person):
    position = models.CharField(max_length=100)
    salary = models.DecimalField(max_digits=10, decimal_places=2)

In this example, Employee inherits from Person, and a new table is created in the database for each model. A OneToOneField is automatically created between Person and Employee.

3. Proxy models

A proxy model is a model that extends another model but does not create a new database table. Instead, a proxy model shares the same database table as the model it extends. Proxy models are useful when you want to add custom methods or change the default manager of a model without affecting the original model.

Example:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    publication_date = models.DateField()

    def __str__(self):
        return self.title

class AlphabeticalBookManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().order_by('title')

class AlphabeticalBook(Book):
    objects = AlphabeticalBookManager()

    class Meta:
        proxy = True

    def author_upper(self):
        return self.author.upper()

In this example, AlphabeticalBook is a proxy model for the Book model. It defines a custom manager AlphabeticalBookManager that sorts books alphabetically by title. It also adds a new method author_upper that returns the uppercase author name.

In this tutorial, we covered the three types of model inheritance in Django: abstract base classes, multi-table inheritance, and proxy models. Each inheritance model has its use cases, and you can choose the most suitable one based on your application's requirements.

  1. Using abstract base classes in Django models:

    When you want to share fields and methods among multiple models, you can use abstract base classes. These classes don't create database tables on their own and are meant for inheritance.

    from django.db import models
    
    class BaseClass(models.Model):
        common_field = models.CharField(max_length=100)
    
        class Meta:
            abstract = True
    
    class MyModel(BaseClass):
        additional_field = models.IntegerField()
    
  2. Inheriting models in Django with three levels:

    You can create a three-level inheritance by extending models successively. Each level adds new fields and functionality.

    from django.db import models
    
    class Level1(models.Model):
        field_level1 = models.CharField(max_length=100)
    
    class Level2(Level1):
        field_level2 = models.IntegerField()
    
    class Level3(Level2):
        field_level3 = models.BooleanField()