Graphene: How to define a schema that has cross references?

Created on 12 Dec 2016  路  2Comments  路  Source: graphql-python/graphene

@syrusakbary
Hi, I recently encountered the following issue when using graphene:

My desired schema:

class Artist(graphene.ObjectType):
    id = graphene.ID()
    famous_song = graphene.Field(Song)

class Song(graphene.ObjectType):
    id = graphene.ID()
    artist = graphene.Field(Artist)

As you can see, Artist and Song are referencing each other, which will inevitably leads to error in python. It would complain something like Song is not defined.

I think this is actually a pretty common scenario, just wonder how to do this in graphene.
Thanks!

Most helpful comment

You can utilize the dynamic field type by using lambda:

famous_song = graphene.Field(lambda: Song)

All 2 comments

You can utilize the dynamic field type by using lambda:

famous_song = graphene.Field(lambda: Song)

@angieellis Great! Thank you very much! This works. :hooray:

Didn't look closely to the source code, there's actually example in the tests:

https://github.com/graphql-python/graphene/blob/master/graphene/types/tests/test_field.py#L60

Was this page helpful?
0 / 5 - 0 ratings