我想让一个模型继承自一个超类,因为超类(“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
解决方案是为此使用django插件。有几个这样的插件存在,我最终使用django多态
相关问题 更多 >
编程相关推荐