【问题标题】:Python GraphQL How to declare a self-referencing graphene object typePython GraphQL 如何声明一个自引用的石墨烯对象类型
【发布时间】:2020-02-25 16:25:50
【问题描述】:

我有一个 django 模型,它有一个与自身相关的外键,我想将此模型表示为石墨烯 ObjectType。

我知道使用 graphene_django 库中的 DjangoObjectType 来做这件事很简单。

我正在寻找一个不使用 graphene_django 的优雅 python 解决方案。

我要代表的模型示例

# models.py
class Category(models.Model):
    name = models.CharField(unique=True, max_length=200)
    parent = models.ForeignKey(
        'self', on_delete=models.SET_NULL, null=True, blank=True,
        related_name='child_category')

下面的架构显然无法扩展,ParentCategoryType 没有parent 字段,因此严格来说它不是CategoryType 的父级。

# schema.py
class ParentCategoryType(graphene.ObjectType):
    id = graphene.types.uuid.UUID()
    name = graphene.String()

class CategoryType(graphene.ObjectType):
    id = graphene.types.uuid.UUID()
    name = graphene.String()
    parent = graphene.Field(ParentCategoryType)

下面的代码给出了CategoryType未定义的错误。

#schema.py
class CategoryType(graphene.ObjectType):
    id = graphene.types.uuid.UUID()
    name = graphene.String()
    parent = graphene.Field(CategoryType)

非常感谢任何帮助。

【问题讨论】:

    标签: python recursion graphql


    【解决方案1】:

    在做了一些研究之后,我发现了一个跟踪这个的GitHub issue。答案似乎是here。我自己试过这个,它有效。因此,在您的情况下,您只需将代码更改为阅读 parent = graphene.Field(lambda: ParentCategoryType) 和 parent = graphene.Field(lambda: CategoryType)

    【讨论】:

      猜你喜欢
      • 2017-05-11
      • 2018-03-06
      • 2020-07-27
      • 2017-05-13
      • 2021-07-11
      • 2018-06-28
      • 2018-03-11
      • 1970-01-01
      • 2018-07-06
      相关资源
      最近更新 更多