7

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.

Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99
karlosss
  • 2,816
  • 7
  • 26
  • 42

4 Answers4

16

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()
Aidas Bendoraitis
  • 3,965
  • 1
  • 30
  • 45
Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99
  • What is the purpose of `django_model` field? – karlosss Apr 04 '19 at 21:18
  • Good catch -- it was leftover from code I used to create the example. Not needed so I removed from example. – Mark Chackerian Apr 04 '19 at 21:55
  • Thanks, now it makes compete sense. – karlosss Apr 04 '19 at 21:56
  • I started to feel `GraphQL` is fit for `Read` not for `Create/Update/Delete`. Even upload `Files`. I have to customized by myself. `DRF` is the good one IMO – joe Dec 30 '19 at 07:04
  • I agree for uploading / downloading files. See my answer on this https://stackoverflow.com/questions/49503756/how-can-i-upload-and-download-files-with-graphene-django/49516843#49516843 – Mark Chackerian Dec 30 '19 at 20:02
  • GraphQL is awesome for create, update, and delete especially if you are using a library like apollo on the FE. Automatic cache updates are super nice and really help reduce the complexity of your FE state management logic. I think most of the GraphQL is bad sentiment in django is because it needs a more robust django and DRF integration. – John Franke Sep 25 '20 at 16:47
5

Here is a small model mutation you can add to your project based on the relay ClientIDMutation and graphene-django's SerializerMutation. I feel like this or something like this should be part of graphene-django.

import graphene
from graphene import relay
from graphql_relay.node.node import from_global_id
from graphene_django.rest_framework.mutation import SerializerMutationOptions

class RelayClientIdDeleteMutation(relay.ClientIDMutation):
     id = graphene.ID()
     message = graphene.String()

     class Meta:
         abstract = True

     @classmethod
     def __init_subclass_with_meta__(
         cls,
         model_class=None,
         **options
     ):
         _meta = SerializerMutationOptions(cls)
         _meta.model_class = model_class
         super(RelayClientIdDeleteMutation, cls).__init_subclass_with_meta__(
             _meta=_meta,  **options
         )

     @classmethod
     def get_queryset(cls, queryset, info):
          return queryset

     @classmethod
     def mutate_and_get_payload(cls, root, info, client_mutation_id):
         id = int(from_global_id(client_mutation_id)[1])
         cls.get_queryset(cls._meta.model_class.objects.all(),
                     info).get(id=id).delete()
         return cls(id=client_mutation_id, message='deleted')

Use

class DeleteSomethingMutation(RelayClientIdDeleteMutation):
     class Meta:
          model_class = SomethingModel

You can also override get_queryset.

John Franke
  • 1,444
  • 19
  • 23
2

I made this library for simple model mutations: https://github.com/topletal/django-model-mutations , you can see how to delete user(s) in examples there

class UserDeleteMutation(mutations.DeleteModelMutation):
    class Meta:
        model = User
T. Opletal
  • 2,124
  • 1
  • 15
  • 23
1

Going by the Python + Graphene hackernews tutorial, I derived the following implementation for deleting a Link object:

class DeleteLink(graphene.Mutation):
    # Return Values
    id = graphene.Int()
    url = graphene.String()
    description = graphene.String()

    class Arguments:
        id = graphene.Int()

    def mutate(self, info, id):
        link = Link.objects.get(id=id)
        print("DEBUG: ${link.id}:${link.description}:${link.url}")
        link.delete()

        return DeleteLink(
            id=id,  # Strangely using link.id here does yield the correct id
            url=link.url,
            description=link.description,
        )


class Mutation(graphene.ObjectType):
    create_link = CreateLink.Field()
    delete_link = DeleteLink.Field()
arhak
  • 2,488
  • 1
  • 24
  • 38
Manav Kataria
  • 5,060
  • 4
  • 24
  • 26