开发者

Django - Introspect django Model in a method implemented in its abstract ancestor?

开发者 https://www.devze.com 2023-01-07 16:00 出处:网络
In django, I would like to reference the class whose method is being called, where the met开发者_开发百科hod itself is implemented in its abstract ancestor.

In django, I would like to reference the class whose method is being called, where the met开发者_开发百科hod 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.


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消