Python GraphQL 如何声明一个自引用的 graphene 对象类型

9

我有一个 Django 模型,它具有与自身相关的外键,我想将此模型表示为 graphene 的 ObjectType

我知道使用 graphene_django 库中的 DjangoObjectType 很容易做到这一点。

我正在寻找一种优雅的 Python 解决方案,而不使用 graphene_django。

我想要表示的模型示例:

# 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)

非常感谢您的帮助。

1个回答

13

在做一些研究后,我发现了一个跟这个问题有关的GitHub问题。答案似乎在这里。我自己尝试了一下,它是有效的。所以在你的情况下,你只需要更改代码为parent = graphene.Field(lambda: ParentCategoryType)parent = graphene.Field(lambda: CategoryType)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接