Order of mixins

You might have come across code with several mixins as follows:

class ComplexView(MyMixin, YourMixin, AccessMixin, DetailView): 

It can get quite tricky figuring out the order to list the base classes. Like most things in Django, the normal rules of Python apply. Python's Method Resolution Order (MRO) determines how they should be arranged.

In a nutshell, mixins come first and base classes come last. The more specialized the parent class is, the more it moves to the left. In practice, this is the only rule you will need to remember.

To understand why this works, consider the following simple example:

class A: def do(self): print("A") class B: def do(self): print("B") class BA(B, A): pass class AB(A, B): pass BA().do() # Prints ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.