在石墨烯python中访问父级字段的内容

时间:2019-07-08 15:12:06

标签: graphql graphene-python

我在python中使用石墨烯。

假设我具有以下架构:

extends type Query {
    a(search:String):A 
}

type A {
    b:B
    important_info:ID
}

type B {
  fieldone: String
  fieldtwo: String
}

现在我要查询:

query {
   a(search:"search string") {
       b {
            fieldone
         }
   }
}

但是fieldone是基于important_info的。

我的课程B如下:

class B(graphene.ObjectType):
    fieldone = graphene.String()
    fieldtwo = graphene.String()

    def resolve_fieldone(self,info):
        # Here I want access to important_info, but I don't know how ...

        return "something based on important_info"

如何从important info的解析器中访问fieldone

1 个答案:

答案 0 :(得分:0)

似乎没有针对此要求的明显或记录在案的解决方案。

我通过将根对象添加到最外层类型中的 info.context 来解决它:

class B(ObjectType):
    c = String()

    def resolve_c(parent, info):
        return 'foo' if info.context['z'] == '' else 'bar'

class A(ObjectType):
    b = Field(B)

    def resolve_b(parent, info):
        return parent.b

class Query(ObjectType):
    a = Field(A)
    z = String()

    def resolve_a(parent, info):
        return some_function_to_get_a()


    def resolve_z(parent, info):
        z = some_function_to_get_z()
        info.context['z'] = z

        return z