How to do mutation query in graphql in django?

by raven_corwin , in category: Javascript , 4 months ago

How to do mutation query in graphql in django?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 4 months ago

@raven_corwin 

In GraphQL, a mutation is used to make changes to the data in the server, such as creating, updating, or deleting records. In Django, you can create mutation queries using the Graphene library, which allows you to define schema for your GraphQL API.


Here's an example of how you can create a mutation query in Django using Graphene:


First, define your mutation class by extending the graphene.Mutation class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import graphene
from .models import YourModel

class YourModelMutation(graphene.Mutation):
    class Arguments:
        # Define the input arguments for your mutation
        field1 = graphene.String(required=True)
        field2 = graphene.Int()

    # Define the output fields for your mutation
    your_field = graphene.Field(YourModelType)

    def mutate(self, info, field1, field2):
        # Create a new instance of YourModel with the input arguments
        new_instance = YourModel(field1=field1, field2=field2)
        new_instance.save()

        # Return the newly created instance
        return YourModelMutation(your_field=new_instance)


Next, create a mutation class that extends the graphene.ObjectType class and define the mutations that you want to expose:

1
2
class Mutation(graphene.ObjectType):
    create_your_model = YourModelMutation.Field()


Finally, include the Mutation class in your schema definition:

1
schema = graphene.Schema(query=Query, mutation=Mutation)


Now you can run a mutation query to create a new instance of YourModel by sending a POST request with the following GraphQL query:

1
2
3
4
5
6
7
8
9
mutation {
  createYourModel(field1: "value1", field2: 123) {
    yourField {
      id
      field1
      field2
    }
  }
}


This will create a new instance of YourModel with the specified input fields and return the newly created instance in the response.