When ``Question`` is published as a ``DjangoObjectType`` and you want to add ``Category`` as a query-able field like so:
..code:: python
class QuestionType(DjangoObjectType):
class Meta:
model = Question
only_fields = ('category',)
Then all query-able related models must be defined as DjangoObjectType subclass,
or they will fail to show if you are trying to query those relation fields. You only
need to create the most basic class for this to work:
..code:: python
class CategoryType(DjangoObjectType):
class Meta:
model = Category
Default QuerySet
-----------------
If you are using ``DjangoObjectType`` you can define a custom `get_queryset` method.
Use this to control filtering on the ObjectType level instead of the Query object level.
..code:: python
from graphene_django.types import DjangoObjectType
from .models import Question
class QuestionType(DjangoObjectType):
class Meta:
model = Question
@classmethod
def get_queryset(cls, queryset, info):
if info.context.user.is_anonymous:
return queryset.filter(published=True)
return queryset
Resolvers
---------
When a GraphQL query is received by the ``Schema`` object, it will map it to a "Resolver" related to it.
This resolve method should follow this format:
..code:: python
def resolve_foo(self, info, **kwargs):
Where "foo" is the name of the field declared in the ``Query`` object.
..code:: python
class Query:
foo = graphene.List(QuestionType)
def resolve_foo(self, info, **kwargs):
id = kwargs.get('id')
return QuestionModel.objects.get(id)
Arguments
~~~~~~~~~
Additionally, Resolvers will receive **any arguments declared in the field definition**. This allows you to provide input arguments in your GraphQL server and can be useful for custom queries.
For more information and more examples, please see the `core object type documentation <https://docs.graphene-python.org/en/latest/types/objecttypes/>`__.
Relay
-----
`Relay <http://docs.graphene-python.org/en/latest/relay/>`__ with Graphene-Django gives us some additional features:
- Pagination and slicing.
- An abstract ``id`` value which contains enough info for the server to know its type and its id.
There is one additional import and a single line of code needed to adopt this:
Note that relay implements :code:`pagination` capabilities automatically, adding a :code:`pageInfo` element, and including :code:`cursor` on nodes. These elements are included in the above example for illustration.
To learn more about Pagination in general, take a look at `Pagination <https://graphql.org/learn/pagination/>`__ on the GraphQL community site.