简体   繁体   中英

Django model inheritance - Subclass instantiated as super when querying

I want to have a model inherit from a superclass, as the superclass ("Step") provides basic functionality to the subclasses ("InfoStep", etc).

However, when i query for "Step", the InfoStep is instantiated as a Step and thus does not call the correct method in the subclass. Step.json() is being called from Route.json() instead of the desired call to InfoStep.json()

Obviously i would much prefer not having to query every subclass explicitly. Minimal code example below:

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

The solution is to use a django plugin for this. Several of such plugins exists, i ended up using django-polymorphic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM