Django: Order of mixins

While writing a python application you might have used view mixins, which are helpful for maintaining DRY code in class-based views. While using these mixins, a common question would have came to surface while using more than one mixin. And that in which order the mixins get executed.

For example, you might have come across code with several mixins as follows:

 

However, it is tricky to find out the order to list the base classes. Here also in Django, the normal rules of Python apply. So, using Python’s Method Resolution Order (MRO) determines how they should be arranged.

Let’s take an example. Consider the following simple example:

As demonstrated in the above code, if Employee is used before Developer in the list of base classes, then Employee’s method gets called and vice versa.

Python’s MRO follows a depth-first, left-to-right order to select a method in the class hierarchy. More details can be found at https://www.python.org/download/releases/2.3/mro/

Leave a Reply

Your email address will not be published. Required fields are marked *