python - Django多表继承和 Graphite 烯

标签 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,但我一直无法弄清楚。任何提示表示赞赏!

最佳答案

您可以通过在 BaseModelType 类中声明附加字段和解析方法来实现:

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
    }
  }
}

关于python - Django多表继承和 Graphite 烯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49737118/

相关文章:

python - 在python中获取绝对文件/目录路径

Python try except 在 sql server 中删除或创建表

python - 我如何使用类别中值进行 df.fillna

python - 如何编译整个 Python 库(包括依赖项)以便它可以在 C 中使用?

python - 将表示时间戳列表的字符串转换为时间戳列表

python-3.x - Ean-128 python 条形码生成器

Django 与 nginx 总是返回错误 404

javascript - GatsbyJS 不变违规 : Encountered an error trying to infer a GraphQL type

javascript - React Router 重定向错误 404

go - Vue Apollo : variables are not added to graphql query, 或者我没有在后端正确接受它们 (Golang)