在我的结构中,我想引入如下循环依赖,以避免向后端提交两个单独的查询。有人可以建议如何在 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)
测试.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)
最佳答案
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
关于python - 具有循环依赖的 GraphQL 设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62773292/