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

This is a question about Python Mixins that may be useful in general. I just use Django models as this is the most suitable use case.

Should mixin inherit from the class it is intended to mix with or from an object?

Code examples, more correct or better, or better, depending on what you want to achieve?

it

class TaggingMixin(models.Model): tag = models.ForeignKey(Tag) class Meta: abstract = True class MyModel(models.Model, TaggingMixin): title = models.CharField(max_length=100) 

Or that:

 class TaggingMixin(object): tag = models.ForeignKey(Tag) class Meta: abstract = True class MyModel(models.Model, TaggingMixin): title = models.CharField(max_length=100) 

I think object inheritance is correct. But I see examples of the first case throughout the network ...

EDIT: I moved my next question to a separate question: Django Abstract Models vs. plain Python mixins vs Python ABC

+44
python
Jul 15 '10 at 9:57
source share
4 answers

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

The right way to structure your mixes using the above example 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:

  • Mixins inherit from model.Model , but are configured as an abstract class.
  • Since mixins inherit from model.Model , your actual model should not inherit from it. If you do this, this may cause an exception to the method matching order.
+43
Sep 12 '14 at 21:37
source share

I would recommend that it inherit from object . This way you can guarantee that it provides only those methods and attributes that you really define explicitly.

In addition, you should always make sure to put the mixin class first when defining your specific class. Python permission rules mean that superclasses are executed in the order they are defined in the class declaration, and permission stops when the corresponding attribute is found. Therefore, if your mixin defines a method that is also defined by the main superclass, your mixin method will not be found.

+12
Jul 15 '10 at 10:02
source share

It looks like work for an abstract model .

EDIT:

These are not mixers per se. Rather, they do not have to be. You can directly get an abstract model.

+6
Jul 15 '10 at 10:01
source share

When you inherit from a simple Python object, the south does not create a migration, so you cannot use this approach

+3
Jul 09 '13 at 11:15
source share



All Articles