Amelse Etomer
Amelse Etomer

Reputation: 1253

access content of parent's field in graphene python

I am using graphene in python.

Let's say I have the following schema:

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

type A {
    b:B
    important_info:ID
}

type B {
  fieldone: String
  fieldtwo: String
}

Now I'd like to query:

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

however fieldone is based on important_info.

My class B looks like this:

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"

How can I access important info from within the resolver of fieldone?

Upvotes: 4

Views: 1193

Answers (1)

timo.rieber
timo.rieber

Reputation: 3867

It seems there is no obvious or documented solution for this requirement.

I solved it by adding the root object to info.context within the outermost type:

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

Upvotes: 2

Related Questions