Skip to content

Commit 3f6c3a7

Browse files
committed
Clean up doc and add resolve_type documentation
1 parent 43e8776 commit 3f6c3a7

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

docs/types/interfaces.rst

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ For example, you can define a field ``hero`` that resolves to any
8383
hero = graphene.Field(
8484
Character,
8585
required=True,
86-
episode=graphene.Field(Episode, required=True)
86+
episode=graphene.Int(required=True)
8787
)
8888
8989
def resolve_hero(_, info, episode):
@@ -92,6 +92,8 @@ For example, you can define a field ``hero`` that resolves to any
9292
return get_human(name='Luke Skywalker')
9393
return get_droid(name='R2-D2')
9494
95+
schema = graphene.Schema(query=Query, types=[Human, Droid])
96+
9597
This allows you to directly query for fields that exist on the Character interface
9698
as well as selecting specific fields on any type that implments the interface
9799
using `inline fragments <https://graphql.org/learn/queries/#inline-fragments>`_.
@@ -100,7 +102,7 @@ For example, the following query:
100102

101103
.. code::
102104
103-
query HeroForEpisode($episode: Episode!) {
105+
query HeroForEpisode($episode: Int!) {
104106
hero(episode: $episode) {
105107
__typename
106108
name
@@ -140,3 +142,32 @@ And different data with the variables ``{ "episode": 5 }``:
140142
}
141143
}
142144
}
145+
146+
Resolving data objects to types
147+
-------------------------------
148+
149+
As you build out your schema in Graphene it is common for your resolvers to
150+
return objects that represent the data backing your GraphQL types rather than
151+
instances of the Graphene types (e.g. Django or SQLAlchemy models). However
152+
when you start using Interfaces you might come across this error:
153+
154+
.. code::
155+
156+
"Abstract type Character must resolve to an Object type at runtime for field Query.hero ..."
157+
158+
This happens because Graphene doesn't have enough information to convert the
159+
data object into a Graphene type needed to resolve the ``Interface``. To solve
160+
this you can define a ``resolve_type`` class method on the ``Interface`` which
161+
maps a data object to a Graphene type:
162+
163+
.. code:: python
164+
165+
class Character(graphene.Interface):
166+
id = graphene.ID(required=True)
167+
name = graphene.String(required=True)
168+
169+
@classmethod
170+
def resolve_type(cls, instance, info):
171+
if instance.type == 'DROID':
172+
return Droid
173+
return Human

0 commit comments

Comments
 (0)