【问题标题】:Django multi-table inheritance and grapheneDjango多表继承和石墨烯
【发布时间】:2018-09-19 02:21:50
【问题描述】:

我正在尝试通过 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,但我无法弄清楚。任何提示表示赞赏!

【问题讨论】:

    标签: python django graphql graphene-python


    【解决方案1】:

    您可以通过在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
        }
      }
    }
    

    【讨论】:

    • 它几乎可以工作了。我不得不按照docs.djangoproject.com/en/1.11/topics/db/models/…first_child = self.childmodel_set.first() 替换为first_child = self.childmodel,但除此之外,这很棒。谢谢!
    • @LaurentS 我假设您有 ChildModel 类,该类具有 ForeignKey 字段到 BaseModel 没有指定 related_name 参数
    • @LaurentS 没有注意到您的 childmodel 类是从 basemodel 派生的
    猜你喜欢
    • 2017-05-13
    • 2017-08-20
    • 2018-01-11
    • 2020-09-01
    • 2017-05-11
    • 2019-05-03
    • 2017-02-26
    • 2019-12-20
    • 2018-06-28
    相关资源
    最近更新 更多