'How to customize graphene-django response?

I have a GraphQL API with graphene-django and I want to customize the query response. 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?



Solution 1:[1]

I'm not sure of a simple way of doing it in graphene-django/python. It seems like there are ways to achieve this in 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. This means your extra_field will always be there, but it will be inside 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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rymanso