Find object in child class from object in parent class in django

后端 未结 6 1753
春和景丽
春和景丽 2021-01-02 17:46

Let\'s say I have a parent class (ThingsThatMigrate) and two children (Coconut and Swallow). Now let\'s say I have a ThingsThatMigrate object. How can I determine if it is

6条回答
  •  鱼传尺愫
    2021-01-02 18:03

    On a Django CMS I work with (Merengue http://www.merengueproject.org/), we store the "classname" attribute that stores what is the real class of the object.

    In order to get the real instance we used the following method:

        def get_real_instance(self):
            """ get object child instance """
            def get_subclasses(cls):
                subclasses = cls.__subclasses__()
                result = []
                for subclass in subclasses:
                    if not subclass._meta.abstract:
                        result.append(subclass)
                    else:
                        result += get_subclasses(subclass)
                return result
    
            if hasattr(self, '_real_instance'):  # try looking in our cache
                return self._real_instance
            subclasses = get_subclasses(self.__class__)
            if not subclasses:  # already real_instance
                self._real_instance = getattr(self, self.class_name, self)
                return self._real_instance
            else:
                subclasses_names = [cls.__name__.lower() for cls in subclasses]
                for subcls_name in subclasses_names:
                    if hasattr(self, subcls_name):
                        return getattr(self, subcls_name, self).get_real_instance()
                return self
    

    The important thing of this function is that it keeps in mind if the class is abstract or not, wich change the logic a little bit.

提交回复
热议问题