Django Model Inheritance query a central table
I have a solution that I thought I could take care of model inheritance, but now looking at it again it doesn't actually solve my problem. What I would like is to be able to call one model and then have the fields of the children model accessible to me. With inheritance I still have to put the child model name in the command line which defeats the whole purpose. Here is an example of what I would like:
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
What I would like to be able to do is do a:
module = LessonModule.objects.get(pk=20)
module.render()
And have it run the corresponding render function. For example if the pk aligns with the Note model then it would just return the self.id. Of course this is simplified to what I want to do with these functions.
I don't 开发者_开发问答have to use Model Inheritance. It just looked like the best way of doing this. I just want a central area to look for all the possible modules.
I would also use this to pull all the LessonModules assigned to a Lesson from the lesson foreign key in the LessonModule.
I haven't used it, but this project looks like what you're looking for:
https://code.google.com/p/django-polymorphic-models/
You can request LessonModule.objects.all() and then .downcast() each object automatically into a ProfileImage or a Note.
Or add the PolymorphicMetaclass to your LessonModule to always retrieve ProfileImage and Note objects from a queryset.
Note the cost of extra queries... polymorphism in Django models is done via table joins, not pure python code.
精彩评论