Search code examples
djangographene-pythongraphene-django

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.


Solution

  • 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()