views:

17

answers:

2

In django, I would like to reference the class whose method is being called, where the method itself is implemented in its abstract ancestor.

class AbstractFather(models.Model):
    class Meta:
        abstract = True
    def my_method(self):
        # >>> Here <<<

class Child(AbstractFather):
    pass

I'm looking to do something like:

isinstance(instance, Child):

Of course I can't know within my_method which child Model was called a priori.

A: 

Why do you say that? You absolutely can. AbstractFather is an abstract model, so it will never be instantiated, so you can always be sure that whatever's calling my_method is an instance of a subclass. The syntax you give should work.

Edit So what exactly are you trying to compare against? self in my_method will always be the relevant instance, and its class will always be the specific subclass of AbstractFather. What do you need to check?

Daniel Roseman
What I meant is that I shouldn't hard-code Child within AbstractFather as there are actually Child1, Child2, etc... in that sense a priori AbstractFather isn't aware of its children.
Jonathan
A: 

Trivial and works:

class AbstractFather(models.Model):
    class Meta:
        abstract = True
    def my_method(self,some_instance):
        print isinstance(some_instance,self.__class__)

class Child(AbstractFather):
    pass
Jonathan