微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 graphQL 查询的上下文之外使用 Graphene-Django 序列化 Django 模型

如何解决如何在 graphQL 查询的上下文之外使用 Graphene-Django 序列化 Django 模型

我正在使用 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 举报,一经查实,本站将立刻删除。