2.0 KiB
2.0 KiB
Fields
Graphene-Django provides some useful fields to help integrate Django with your GraphQL Schema.
DjangoListField
DjangoListField
allows you to define a list of DjangoObjectType<queries-objecttypes>
's. By default it will resolve the default queryset of the Django model.
from graphene import ObjectType, Schema
from graphene_django import DjangoListField
class RecipeType(DjangoObjectType):
class Meta:
= Recipe
model = ("title", "instructions")
fields
class Query(ObjectType):
= DjangoListField(RecipeType)
recipes
= Schema(query=Query) schema
The above code results in the following schema definition:
schema {
query: Query
}
type Query {
recipes: [RecipeType!]
}
type RecipeType {
title: String!
instructions: String!
}
Custom resolvers
If your DjangoObjectType
has defined a custom get_queryset<django-objecttype-get-queryset>
method, when resolving a DjangoListField
it will be called with either the return of the field resolver (if one is defined) or the default queryset from the Django model.
For example the following schema will only resolve recipes which have been published and have a title:
from graphene import ObjectType, Schema
from graphene_django import DjangoListField
class RecipeType(DjangoObjectType):
class Meta:
= Recipe
model = ("title", "instructions")
fields
@classmethod
def get_queryset(cls, queryset, info):
# Filter out recipes that have no title
return queryset.exclude(title__exact="")
class Query(ObjectType):
= DjangoListField(RecipeType)
recipes
def resolve_recipes(parent, info):
# Only get recipes that have been published
return Recipe.objects.filter(published=True)
= Schema(query=Query) schema
DjangoConnectionField
TODO