django, python

What is Abstract Base Class in Django

What is Abstract Base Class in Django

What is Abstract Base Class in Django and how we can use it in our applications?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. One of the principles of Python is “Do not repeat yourself”.  Abstract models in Django are meant to do exactly that.

In Django normally Database tables are created from models. Sometimes we have the same fields which we use in other models. So in this case we won’t repeat these fields. In such cases, Abstract classes are useful. For creating Abstract Base classes we add abstract=True to our model’s meta class. Django will not create database tables for these models but Models inherited from our Abstract Base class have those fields which are represented in our Abstract Base Class.

For example, we want to add created_at and updated_at columns to all our models to track entries created and updated time. In this case, We will not repeatedly add these fields to all our models. Instead of it, We will create our Abstract Base Class and all our other models inherited from this base class.

Django Abstract Model Usage

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

    class Meta:
        abstract = True
        ordering = ("created_at",)

class Category(DateTimeLog):
    name = models.CharField(max_length=255)

class Post(DateTimeLog):
    title = models.CharField(max_length=255)
    description = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True)

Here Django will not create a database table for the DateTimeLog model. But tables were created for the Category and Post model and all of them have created_at and updated_at columns.

Due to the way Python inheritance works, if a child class inherits from multiple abstract base classes, only the meta options from the first listed class will be inherited by default.

In the end, remember that Django will not inherit abstraction, it means that children of abstract base classes don’t automatically become abstract classes themselves. If we want it to be abstract, we have to declare it in our meta class again.

Read more in Documentation.


Tagged , , , ,

Leave a Reply

Your email address will not be published.