简体   繁体   English

Python GraphQL 如何声明自引用石墨烯 object 类型

[英]Python GraphQL How to declare a self-referencing graphene object type

I have a django model which has a foreign key related to itself, I want to represent this model as a graphene ObjectType .我有一个 django model 有一个与自身相关的外键,我想将此 model 表示为石墨烯ObjectType

I know it is trivial to do this using DjangoObjectType from the graphene_django library.我知道使用 graphene_django 库中的DjangoObjectType执行此操作很简单。

I am looking for an elegant python solution without using graphene_django.我正在寻找一个优雅的 python 解决方案,而不使用 graphene_django。

An example of a model I want to represent我要代表的 model 的一个例子

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

the schema below obviously does not scale and the ParentCategoryType does not have the parent field so it is not strictly a parent of CategoryType .下面的架构显然无法扩展,并且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)

the code below gives a CategoryType undefined error.下面的代码给出了CategoryType未定义的错误。

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

Any help much appreciated.非常感谢任何帮助。

After doing some research, I came across a GitHub issue that tracks this.在做了一些研究之后,我遇到了一个跟踪此问题的GitHub 问题 The answer seems to be here .答案似乎就在这里 I tried this myself and it works.我自己试过这个,它有效。 So in your case, you would just change the code to read parent = graphene.Field(lambda: ParentCategoryType) and parent = graphene.Field(lambda: CategoryType)因此,在您的情况下,您只需将代码更改为parent = graphene.Field(lambda: ParentCategoryType)parent = graphene.Field(lambda: CategoryType)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM