简体   繁体   English

如何自定义 graphene-django 响应?

[英]How to customize graphene-django response?

I have a GraphQL API with graphene-django and I want to customize the query response.我有一个带有 graphene-django 的 GraphQL API,我想自定义查询响应。 Here is the default response;这是默认响应;

{
  "data": {
    "materials": {

    }
  },
  "errors": {

  }
}

However, I want to customize it like this;但是,我想像这样自定义它;

{
  "data": {
    "materials": {

    }
  },
  "errors": {

  },
  "extra_field": {

  }
}

How can I do this?我怎样才能做到这一点?

I'm not sure of a simple way of doing it in graphene-django/python.我不确定在 graphene-django/python 中做这件事的简单方法。 It seems like there are ways to achieve this in NodeJS.似乎有办法在 NodeJS 中实现这一点。 However if your goal is to add some data to every single response, you can make a super class that all your classes inherit from.但是,如果您的目标是向每个响应添加一些数据,则可以制作一个超级 class,您的所有类都从中继承。 This means your extra_field will always be there, but it will be inside data .这意味着您的extra_field将始终存在,但它将在data内。

class MyBaseType(DjangoObjectType):
    class Meta:
        abstract = True

    extra_field = graphene.JSONField()

    def resolve_extra_field(self, info):
        return #something

And then inherit in your normal classes.然后在你的普通类中继承。

class UserType(MyBaseType):
    class Meta:
        model = User

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM