Gilang Chandrasa Thoughts, stories, and ideas

Django Model Inheritance with Custom Manager

If you have multiple classes with the same attribute(s) and custom queryset(s) it make sense to use Django inheritance feature. Define parent class with abstract = True and set that custom manager on the parent class.

from django.db import models

class BaseQuerySet(models.QuerySet):
    def active(self):
        return self.filter(is_active=True)

class Parent(models.Model):
    is_active = models.BooleanField(default=True)
    objects = BaseQuerySet.as_manager()

    class Meta:
        abstract = True

Define the children class and inherit from previous Parent class.

class ChildrenA(Parent):
    name = models.CharField(max_length=255)

class ChildrenB(Parent):
    title = models.CharField(max_length=255)

Both ChildrenA and ChildrenB have is_active attribute and custom queryset active.'Gilang')'Awesome')