Django模型继承在其他模型的领域

时间:2012-07-28 11:31:07

标签: django django-models django-orm django-inheritance

我有以下型号:

class Engine(models.Model):
    ...
    def speed(self):
        return 100
    objects = InheritanceManager()

class TurboEngine(Engine):
    ...
    def speed(self):
        return 500

class Car(models.Model):
    ...
    engine = models.ForeignKey(Engine)

否我在Car上使用带有TurboEngine的DetailView,但car.engine.speed()返回100.如何让它选择正确的类?

1 个答案:

答案 0 :(得分:3)

这是一个非常好的和感兴趣的问题,我们在2年或3年前遇到了同样的问题:

class RealInstaceProvider(object):
    def get_real_instance(self):
        """
        Makes a SQL sentence which does the JOIN with its real model class
        """

        if hasattr(self, '_real_instance'):  # try looking in our cache
            return self._real_instance
        subclasses = self.__class__.__subclasses__()
        if not subclasses:  # already real_instance
            real_instance = getattr(self, self.__class__.__name__, self)
            self._real_instance = real_instance
            return real_instance
        else:
            subclasses_names = [cls.__name__.lower() for cls in subclasses]
            for subcls_name in subclasses_names:
                if hasattr(self, subcls_name):
                    self._real_instance = getattr(self, subcls_name, self).get_real_instance()
                    return self._real_instance
            self._real_instance = self
            return self

class Engine(models.Model, RealInstaceProvider):
    ...
    def speed(self):
        return 100
    objects = InheritanceManager()

class TurboEngine(Engine):
    ...
    def speed(self):
        return 500

class Car(models.Model):
    ...
    engine = models.ForeignKey(Engine)

你必须访问下一个方式:car.engine.get_real_provider()。speed()