python - 具有循环依赖的 GraphQL 设计

标签 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)
测试.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/

相关文章:

python - GraphQL/Graphene 用于 Django 模板中的后端调用

python - 我如何知道生成器是否从一开始就为空?

python - 如何在 tensorflow 中进行稀疏张量和稠密张量之间的元素乘法?

javascript - GraphQL-工具处理 SchemaError

graphql - 抑制 GraphQL 响应中的重复项

django -\"createUaction\"类型的\"CreateUaction\"字段必须有一个子选择。”

python - Graphite 烯和 Django 的关系

python - Python 的 raw_input() 中的制表符补全

python - "Splat"行,列表分为多行(pandas)

javascript - 为什么 WebStorm 在 Vue 组件或 .graphql 文件中的 apollo 对象内的 gql 查询中显示错误