7

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

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

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

4

4 回答 4

13

像这样的东西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()
于 2019-04-02T15:42:09.943 回答
4

这是一个基于中继 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。

于 2020-09-24T19:57:32.320 回答
2

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

class UserDeleteMutation(mutations.DeleteModelMutation):
    class Meta:
        model = User
于 2019-11-22T11:11:50.630 回答
1

通过Python + Graphene hackernews 教程,我导出了以下用于删除 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()
于 2019-08-17T02:59:11.787 回答