删除Django GraphQL中的突变

kar*_*sss 3 django graphene-python

Graphene-Django 的文档几乎解释了如何创建和更新对象。但是如何删除呢?我可以想象查询看起来像

mutation mut{
  deleteUser(id: 1){
    user{
      username
      email
    }
    error
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我怀疑正确的方法是从头开始编写后端代码。

Mar*_*ian 5

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, **args):
        obj = User.objects.get(args["id")])
        obj.delete()
        return cls(ok=True)


class UserMutations(object):
    delete_user = DeleteUser.Field()
Run Code Online (Sandbox Code Playgroud)


Joh*_*ips 5

这是一个小的模型突变,您可以基于中继 ClientIDMutation 和 graphene-django 的 SerializerMutation 添加到您的项目中。我觉得这个或类似的东西应该是 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')
Run Code Online (Sandbox Code Playgroud)

使用

class DeleteSomethingMutation(RelayClientIdDeleteMutation):
     class Meta:
          model_class = SomethingModel
Run Code Online (Sandbox Code Playgroud)

您还可以覆盖 get_queryset。