Django多表继承和石墨烯

时间:2018-04-09 16:03:09

标签: python django graphql graphene-python

我正在尝试通过django-graphene提供graphql端点。我有以下型号:

class BaseModel(models.Model):
    fk = models.ForeignKey(MainModel, related_name='bases')
    base_info = models.CharField(...)

class ChildModel(BaseModel):
    name = models.CharField(...)

MainModel是我的中心数据模型。 ChildModel有几种变体,它解释了此处使用的多表继承。 我已经能够使用这个模式声明:

class BaseModelType(DjangoObjectType):
    class Meta:
        model = BaseModel

class ChildModelType(DjangoObjectType):
    class Meta:
        model = ChildModel

class MainModelType(DjangoObjectType):
    class Meta:
        model = MainModel

允许以下graphQL查询:

{
  mainModel(id: 123) {
    id
    bases {
      id
      baseInfo
      childmodel {
        id
        name
      }
    }
  }
}

但是,我想以Django理解继承的方式将其弄平,以便我可以像这样查询数据:

{
  mainModel(id: 123) {
    id
    bases {
      id
      baseInfo
      name        <--- this field from the child is now on the base level
    }
  }
}

我怀疑答案在于我如何宣布ChildModelType,但我无法弄明白。任何提示赞赏!

1 个答案:

答案 0 :(得分:0)

您可以通过在BaseModelType class:

中声明其他字段和解析方法来执行此操作
class BaseModelType(DjangoObjectType):
    name_from_child = graphene.String()

    class Meta:
        model = BaseModel

    def resolve_name_from_child(self, info):
        # if ChildModel have ForeignKey to BaseModel
        # first_child = self.childmodel_set.first()

        # for your case with multi-table inheritance
        # ChildModel is derived from BaseModel: class ChildModel(BaseModel):
        first_child = self.childmodel

        if first_child:
            return first_child.name
        return None

查询:

{
  mainModel(id: 123) {
    id
    bases {
      id
      baseInfo
      name_from_child   <--- first child name
    }
  }
}