Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete mutation in Django GraphQL

The docs of Graphene-Django pretty much explains how to create and update an object. But how to delete it? I can imagine the query to look like

mutation mut{
  deleteUser(id: 1){
    user{
      username
      email
    }
    error
  }
}

but i doubt that the correct approach is to write the backend code from scratch.

like image 1000
karlosss Avatar asked Mar 31 '19 14:03

karlosss


People also ask

How do I delete an item in GraphQL?

Using the parse GraphQL, there are two different ways to delete an existing object in your database: Using generic mutation - this is the mutation that you can use to delete an object of any class. Using class mutation - this is the recommended mutation that you should use to delete an object of a specific class.

How do you update data in GraphQL?

Update mutations let you update existing objects of a particular type. With update mutations, you can filter nodes and set or remove any field belonging to a type. We use the following schema to demonstrate some examples. Dgraph automatically generates input and return types in the schema for the update mutation.


1 Answers

Something like this, where UsersMutations is part of your schema:

class DeleteUser(graphene.Mutation):
    ok = graphene.Boolean()

    class Arguments:
        id = graphene.ID()

    @classmethod
    def mutate(cls, root, info, **kwargs):
        obj = User.objects.get(pk=kwargs["id"])
        obj.delete()
        return cls(ok=True)


class UserMutations(object):
    delete_user = DeleteUser.Field()
like image 55
Mark Chackerian Avatar answered Oct 18 '22 10:10

Mark Chackerian