eugene
eugene

Reputation: 41785

Django, inherit models.Model first or non model class first?

Sometimes I see

class Foo(models.Model, NonModelCls):
    pass

Other times, I see

class Bar(NonModelCls, models.Model):
    pass

What's the difference between the two and when should I use each over another?

Upvotes: 1

Views: 152

Answers (1)

kaveh
kaveh

Reputation: 2146

It depends on what you have in NonModelCls. Search order for attributes and methods are from left to right (https://docs.python.org/3/tutorial/classes.html?highlight=inheritence#multiple-inheritance).

Let's say you have these classes:

class A:
    def __init__():
        print('A')
        super(A, self).__init__()


class B:
    def __init__():
        print('B')
        super(B, self).__init__()


class C(A,B):
    pass

class D(B,A):
    pass

Then calling C and D will result in:

>>>C()
A
B
<__main__.C object at 0x7f51d3efe0f0>
>>>D()
B
A
<__main__.D object at 0x7f51d3efe0b8>

So in your case, if NonModelCls has a method with same name as one of models.Model methods, like save, then it will override Model.save in Bar class, while it gets ignored in Foo class.

Upvotes: 1

Related Questions