4

I'm using Graphene-Django to build a GraphQL API, and I've defined object types as explained in the docs. By way of example,

import graphene
from graphene_django import DjangoObjectType

from .models import Question

class QuestionType(DjangoObjectType):
    class Meta:
        model = Question
        fields = ("id", "question_text")

class Query(graphene.ObjectType):
    questions = graphene.List(QuestionType)
    question_by_id = graphene.Field(QuestionType, id=graphene.String())

    def resolve_questions(root, info, **kwargs):
        # Querying a list
        return Question.objects.all()

    def resolve_question_by_id(root, info, id):
        # Querying a single question
        return Question.objects.get(pk=id)

This works fine for fetching the content of a Question model in a GraphQL query, but I'd also like to serialize my Question objects to a JSON representation in log files and tests. I can write a separate utility function, but it seems redundant when I already have an existing GraphQL schema that defines which objects fields I'm interested in and how to serialize them.

Basically, I'm looking for a Graphene analogue to using a DRF serializer

serializer = CommentSerializer(comment)
serializer.data
# {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}

Ideally, I'm looking for something like

from my_app.schema import QuestionType
from my_app.models import Question

question_object = Quest.objects.get(pk=1)
data = QuestionType.to_dict(question_object)

I've looked at the Graphene docs, and poked around the source on Github but it all seems very obfuscated and I can't find an obvious way to do what I want.

Can anyone offer a concise example of using a Graphene ObjectType to serialize a single model instance outside the entire GraphQL query context?

bjmc
  • 2,970
  • 2
  • 32
  • 46

0 Answers0