删除 Django GraphQL 中的突变

Delete mutation in Django GraphQL

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

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

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

类似这样,其中 UsersMutations 是您的架构的一部分:

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

根据 Python + Graphene hackernews tutorial,我导出了以下用于删除 Link 对象的实现:

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

我为简单的模型突变制作了这个库:https://github.com/topletal/django-model-mutations,你可以在示例中看到如何删除用户

class UserDeleteMutation(mutations.DeleteModelMutation):
    class Meta:
        model = User

这是一个小模型突变,您可以基于中继 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')

使用

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

您也可以覆盖 get_queryset。