Django模型继承子类在查询时实例化为super

2024-05-23 14:17:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让一个模型继承自一个超类,因为超类(“Step”)为子类(“InfoStep”等)提供了基本的功能。你知道吗

但是,当我查询“Step”时,InfoStep被实例化为一个Step,因此不会在子类中调用正确的方法。步骤.json()正在从调用路由.json()而不是所需的调用InfoStep.json文件()

显然,我更希望不必显式地查询每个子类。最小代码示例如下:

class Route(models.Model):
  def json(self):
    postResult = []
    for needle in self.posts.all():
      json = needle.json()
      json['steps'] = [x.json() for x in Step.objects.filter(post=needle, route=self)]
      postResult.append(json)

    return postResult


class Step(models.Model):
  def json(self):
        return {'id' : self.id,
                'name' : self.name,
                'description' : self.description}

class InfoStep(Step):
  def json(self):
        base = super(InfoStep, self).json()
        base[0]['url'] = self.url
        return base

Tags: inselfjsonforbasemodelreturnmodels