我有一个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)
任何帮助非常感谢。
在做了一些研究之后,我遇到了一个跟踪这个问题的 GitHub 问题。答案似乎就在这里。我自己试过这个,它有效。因此,在您的情况下,您只需更改代码以读取parent = graphene.Field(lambda: ParentCategoryType)
并parent = graphene.Field(lambda: CategoryType)