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

2024-05-15 11:10:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个django模型,它本身有一个外键,我想用graphene ObjectType来表示这个模型。你知道吗

我知道使用graphenedjango库中的DjangoObjectType来实现这一点很简单。你知道吗

我正在寻找一个优雅的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)

非常感谢您的帮助。你知道吗


Tags: namepy模型idtrueuuidmodelsclass
1条回答
网友
1楼 · 发布于 2024-05-15 11:10:59

在做了一些研究之后,我发现了一个GitHub issue跟踪这个。答案似乎是here。我自己也试过了,效果不错。所以在您的例子中,您只需将代码改为parent = graphene.Field(lambda: ParentCategoryType)parent = graphene.Field(lambda: CategoryType)

相关问题 更多 >