2011-04-20 81 views
2

我有一個解決方案,我認爲我可以照顧模型繼承,但現在再次查看它並不能真正解決我的問題。我想要的是能夠調用一個模型,然後讓我可以訪問子模型的字段。通過繼承,我仍然必須將子模型名稱放在命令行中,這樣才能達到完整的目的。下面是我想什麼一個例子:Django模型繼承查詢中心表

class LessonModule(models.Model): 
    lesson = models.ForeignKey('Lesson') 
    name = models.CharField(max_length=100, blank=True) 


class ProfileImage(LessonModule): 
    file_loc = models.ImageField(upload_to="profiles/") 
    detail_file_loc = models.ImageField(upload_to="profiles/", blank=True) 

    def render(self): 
     t = loader.get_template("template/profile_image.html") 
     c = Context({'image_path': self.file_loc.url}) 
     return t.render(c) 

    def __unicode__(self): 
     return '[prof: %d]' % self.id 

class Note(LessonModule): 
    def __unicode__(self): 
     return '[note: %d]' % self.id 

    def render(self): 
     return self.id 

我想做什麼就能做的是做一個:

module = LessonModule.objects.get(pk=20) 
module.render() 

,並讓它運行相應的渲染功能。例如,如果pk與Note模型對齊,那麼它只會返回self.id。當然,這被簡化爲我想要對這些功能做什麼。

我不必使用模型繼承。它看起來像這樣做的最好方式。我只想要一箇中心區域來尋找所有可能的模塊。

我也會用這個從LessonModule的課程外鍵中提取所有分配給Lesson的LessonModules。

回答

2

我還沒有使用它,但這個項目看起來像你要找的東西:
https://code.google.com/p/django-polymorphic-models/

您可以要求LessonModule.objects.all(),然後.downcast()每個自動轉換成目標一個ProfileImage或一個註釋。

或者將PolymorphicMetaclass添加到您的LessonModule中,以始終從查詢集中檢索ProfileImage和Note對象。

請注意額外查詢的成本... Django模型中的多態性是通過表連接完成的,而不是純粹的Python代碼。

+0

謝謝你終於回答了這個問題。有一陣子了。我必須檢查一下。 – Chris 2011-10-26 16:41:04