2012-07-28 208 views
3

我有以下型號:的Django模型繼承

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使用的DetailView與TurboEngine,但car.engine.speed()回報100如何使它選擇合適的班級?

回答

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()速度()

+0

謝謝,這與小的改動作品: 自.__類__ get_subclasses()應該是自.__類__.__子類__() 和self.class_name應該是自.__類__.__ name__ – 2012-07-28 12:50:09

+0

好吧,我複製並粘貼併爲你概括,我會編輯我的答案 – Goin 2012-07-28 13:27:42

+0

我相信我贏了' t需要'objects = InheritanceManager()',對吧? – 2012-07-28 15:20:07