我有一个 django 模型,它有一个与自身相关的外键,我想将此模型表示为 Graphite 烯 ObjectType
.
我知道使用 DjangoObjectType
做这件事很简单来自 graphene_django 库。
我正在寻找不使用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)
非常感谢任何帮助。
最佳答案
在做了一些研究之后,我遇到了一个 GitHub issue跟踪这个。答案似乎是here .我自己试过这个,它有效。因此,在您的情况下,您只需将代码更改为 parent = graphene.Field(lambda: ParentCategoryType)
和 parent = graphene.Field(lambda: CategoryType)
关于Python GraphQL 如何声明自引用 Graphite 烯对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58624224/