-
Install Django Graphene
pip install graphene-django
settings.py
INSTALLED_APPS = [ ... 'django.contrib.staticfiles', # Required for GraphiQL 'graphene_django' ]
-
Add a GraphQL url
from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView urlpatterns = [ ... path("graphql/", csrf_exempt(GraphQLView.as_view(graphiql=True))), ]
-
Add an empty
Query
schema.py
import graphene class Query(graphene.ObjectType): pass schema = graphene.Schema(query=Query)
settings.py
GRAPHENE = { 'SCHEMA': 'graphene_demo.schema.schema' }
-
Add some fields to the query
class Query(graphene.ObjectType): hello = graphene.String() goodbye = graphene.String()
-
Add resolvers for the fields
class Query(graphene.ObjectType): hello = graphene.String() goodbye = graphene.String() def resolve_hello(self, info): return "Hello world!" def resolve_goodbye(self, info): return "Goodbye cruel world!"
-
Make a field and resolver with parameters
class Query(graphene.ObjectType): hello = graphene.String(name=graphene.String(default_value="world")) goodbye = graphene.String() def resolve_hello(self, info, name): return f"Hello {name}!" def resolve_goodbye(self, info): return "Goodbye cruel world!"
-
Make an application schema and connect it to the main schema
bootcamps/schema.py
from datetime import datetime import graphene class Query(object): thing = graphene.Date() def resolve_thing(parent, info): return datetime.now()
schema.py
import bootcamps.schema class Query(bootcamps.schema.Query, graphene.ObjectType): ...
-
Create our first type
bootcamps/schema.py
from graphene_django import DjangoObjectType from .models import Instructor
class InstructorType(DjangoObjectType): class Meta: model = Instructor
-
Add an
instructors
queryclass Query(object): ... instructors = graphene.List(InstructorType) ... def resolve_instructors(self, info): return Instructor.objects.all()
-
Add a single
instructor
queryclass Query(object): ... instructor = graphene.Field(InstructorType, id=graphene.Int()) ... def resolve_instructor(self, info, id): if id is not None: return Instructor.objects.get(pk=id) return None
-
Simplify using
DjangoListField
from graphene_django import DjangoObjectType, DjangoListField ... class Query(object): instructors = DjangoListField(InstructorType) def resolve_thing(self, info): ... # resolver can be deleted # def resolve_instructors(self, infor): def resolve_instructor(self, info, id): ...
-
Automagic Relationships! 💖
from .models import Instructor, Cohort class CohortType(DjangoObjectType): class Meta: model = Cohort