Graphene: Defining cross-references between objects

Created on 7 Sep 2018  路  3Comments  路  Source: graphql-python/graphene

This is more of a question than a issue.

Suppose the following example:

class Sale(ObjectType):
   pass

class SaleItem(ObjectType):
    sale = Field(Sale)

How can I proceed to add a new field on Sale that references SaleItem, like:

class Sale(ObjectType):
    items = List(SaleItem)

Most helpful comment

@romaia you can lazily reference other types by using a lambda function like this:

class Sale(ObjectType):
    items = List(lambda: SaleItem)

class SaleItem(ObjectType):
    sale = Field(Sale)

You can also specify a full import path as a string (like Django):

# This file is api/definitions/sale.py
class Sale(ObjectType):
    items = List('api.definitions.sale.SaleItem')

class SaleItem(ObjectType):
    sale = Field(Sale)

All 3 comments

@romaia you can lazily reference other types by using a lambda function like this:

class Sale(ObjectType):
    items = List(lambda: SaleItem)

class SaleItem(ObjectType):
    sale = Field(Sale)

You can also specify a full import path as a string (like Django):

# This file is api/definitions/sale.py
class Sale(ObjectType):
    items = List('api.definitions.sale.SaleItem')

class SaleItem(ObjectType):
    sale = Field(Sale)

@jkimbo Thanks so much. I came from JavaScript and completely forgot that arrow functions are just lambda functions 馃槢

You're welcome @mikebobadilla . Glad I could help!

Was this page helpful?
0 / 5 - 0 ratings