问题描述
我正在使用 Graphene-Django 构建一个 GraphQL API,并且我已经 defined object types as explained in the docs。举个例子,
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,id):
# Querying a single question
return Question.objects.get(pk=id)
这适用于在 GraphQL 查询中获取 Question
模型的内容,但我还想将我的 Question
对象序列化为日志文件和测试中的 JSON 表示。我可以编写一个单独的实用程序函数,但是当我已经有一个现有的 GraphQL 模式来定义我感兴趣的对象字段以及如何序列化它们时,这似乎是多余的。
基本上,我正在寻找与 using a DRF serializer 类似的石墨烯
serializer = CommentSerializer(comment)
serializer.data
# {'email': 'leila@example.com','content': 'foo bar','created': '2016-01-27T15:17:10.375877'}
理想情况下,我正在寻找类似的东西
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)
我已经查看了 Graphene 文档,并在 the source on Github 周围闲逛,但这一切似乎都很混乱,我找不到明显的方法来做我想做的事。
谁能提供一个使用 Graphene ObjectType 在整个 GraphQL 查询上下文之外序列化单个模型实例的简明示例?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)