2011-04-20 138 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