循环依赖的GraphQL设计

时间:2020-07-07 10:33:51

标签: python graphql graphene-python

在我的结构中,我想引入如下的循环依赖,以避免向后端提交两个单独的查询。有人可以建议如何使用Python做到这一点。

下面是示例代码:

parent.py

import graphene

class Parent(graphene.ObjectType):
    id = graphene.ID()
    name = graphene.String()
    child= graphene.Field(Child)

child.py

import graphene

class Child(graphene.ObjectType):
    id = graphene.ID()
    name = graphene.String()
    parent = graphene.Field(Parent)

test.py

from parent import Parent

print("TEST")

错误

ImportError: cannot import name 'Parent' from partially initialized module 'parent' (most likely due to a circular import) 

更新 以下内容也不起作用(循环导入错误)

import graphene

class Child(graphene.ObjectType):
    import app.parent as P
    id = graphene.ID()
    name = graphene.String()
    parent = graphene.Field(P.Parent)

...
import graphene

class Parent(graphene.ObjectType):
    import app.child as C
    id = graphene.ID()
    name = graphene.String()
    child = graphene.Field(C.Child)
...

from app.parent import Parent

print("TEST")

AttributeError: partially initialized module 'app.parent' has no attribute 'Parent' (most likely due to a circular import)

1 个答案:

答案 0 :(得分:0)

TLDR -graphene.Field('<class-loc>.<class-name>')。 对于您来说,graphene.Field('parent.Parent')graphene.Field('child.Child')应该可以完成这项工作。

遇到了完全相同的问题,并认为必须有某种方法可以仅使用字符串表示形式来定义架构。在遍历代码时,我发现内部使用了import_string函数,该函数帮助我理解了如何实现-

https://github.com/graphql-python/graphene/blob/a53b782bf8ec5612d5cceb582fbde68eeba859aa/graphene/utils/module_loading.py#L5

相关问题