Skip to content

Model Mixins Pattern

This is under structural pattern.

Pattern a model mixins

  • Problem: Distinct models have the same fields and/or methods duplicated violating the DRY principle.
  • Solution: Extract common fields and methods into various reusable model mixins.

Model mixins

Model mixins are abstract classes that can be added as a parent class of a model. Python supports multiple inheritances, unlike other languages such as Java. Hence, you can list any number of parent classes for a model.

Smaller mixins are better. Whenever a mixin becomes large and violates the single responsibility principle, consider refactoring it into smaller classes. Let a mixin do one thing and do it well.


In our previous example, the model mixin used to update DSFBUFE and NPEJGJFE time can be easily factored out, as shown in the following code:

models.py
class TimeStampModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Postable(TimeStampModel):
    message = models.TextField(max_length=500)

    class Meta:
        abstract = True

class Post(Postable):
    ...

class Comment(Postable):
    ...

We have two base classes now. However, the functionality is clearly separated. The mixin can be separated into its own module and reused in other contexts.