Delete mutation in Django GraphQL
Asked Answered
S

4

8

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.

Senhauser answered 31/3, 2019 at 14:57 Comment(3)
That question does not include Django, I already saw it and it shows how to code it from scratch, which I doubt is the correct way.Senhauser
My bad I will delete itMezuzah
I think there isn't any keyword to do delete, all the existed example shows codes like you wrote.Nunez
H
17

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()
Harmonics answered 2/4, 2019 at 15:42 Comment(6)
What is the purpose of django_model field?Senhauser
Good catch -- it was leftover from code I used to create the example. Not needed so I removed from example.Harmonics
Thanks, now it makes compete sense.Senhauser
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 IMOCasablanca
I agree for uploading / downloading files. See my answer on this #49504256Harmonics
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.Mast
M
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.

Mast answered 24/9, 2020 at 19:57 Comment(0)
E
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
Esthonia answered 22/11, 2019 at 11:11 Comment(0)
W
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()
Washhouse answered 17/8, 2019 at 2:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.