Django Model Mixins: inherit from models.Model or from object?

Django does a lot of meta magic when it comes to its model classes, so unfortunately the usual approach to mixins as suggested in Daniel Roseman’s answer — where they inherit from object — does not work well in the Django universe.

The correct way to structure your mixins, using the example provided, would be:

class TaggingMixin(models.Model):
    tag = models.ForeignKey(Tag)

    class Meta:
        abstract = True

class MyModel(TaggingMixin):
    title = models.CharField(max_length=100)

Important points here being:

  • Mixins inherit from model.Model but are configured as an abstract class.
  • Because mixins inherit from model.Model, your actual model should not inherit from it. If you do, this might trigger a consistent method resolution order exception.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)