2017-06-22 53 views
0

我有一个Post类有几个子类TextPostAudioPost等,每个都有自己的render_html()方法我Django应用程序。从父项调用Django子模型方法需要InheritanceManager?

class Post(models.Model): 
    author = models.ForeinKey(User,...) 
    title = models.CharField(...) 
    pub_date = models.DateTimeField(...) 
    ... 
    def render_html(self): 
     return "rendered title, author date" 

class AudioPost(Post): 
    audioFile = FileField(...) 
    def render_html(self): 
     return "Correct audio html" 
... 

每个子模型都有用于上传,验证和保存规则的ModelForm

在主页视图中,我想采取所有帖子,按日期排列并呈现它们。对我来说,这应该是越简单

## in view 
context = { 'posts' : Post.objects.order_by('-pub_date')[:5] } 

## in template 
{{ post.render_html() | safe }} 

我记住的东西在Java中抽象类以这种方式工作。但是当我用Python这样做时,render_html方法被调用,就好像它们是父类的每个成员一样。我查了一下Django如何实现多表继承,看来我需要逐个检查生成的OneToOneFields,直到找到一个不引发异常的事件,或者使用InheritanceManager实用程序管理器。这两种方式之一是做这件事的最佳方式还是我应该做其他事情?

+0

因为他们*是他们的父类的*成员。如果您查询帖子,那么您将获得帖子。 –

回答

0

我会建议你的问题的另一种方法,你可以用它来获得基类的所有子类。这将是一个位的方便,因为你不需要得到查询集的每一个儿童类手动

qerysets_child = [child_cls.objects.all() for child_cls in vars()['BaseClass'].__subclasses__()] 

你指的方法,其适用于Java,但我不认为这能在这里工作。您可以手动使用子类或获取具有上述子类功能的所有子类。

0

我通过以下方法中Post解决了这个,让我做

{{ post.get_subclass().render_html() }} 

在模板中。假设4个小类,AudioPostVideoPostTextPostRichTextPost

from django.db import models 
from django.core.exceptions import ObjectDoesNotExist 

class Post(models.Model): 
    ... 

    ... 
    def get_subclass(self): 
     try: 
      textpost = self.textpost 
      return textpost 
     except ObjectDoesNotExist: 
      pass 

     try: 
      audiopost = self.audiopost 
      return audiopost 
     except ObjectDoesNotExist: 
      pass 

     try: 
      videopost = self.videopost 
      return videopost 
     except ObjectDoesNotExist: 
      pass 

     try: 
      richtextpost = self.richtextpost 
      return richtextpost 
     except ObjectDoesNotExist: 
      pass 

     raise ObjectDoesNotExist