【问题标题】:Delete mutation in Django GraphQL在 Django GraphQL 中删除突变
【发布时间】:2019-08-21 20:32:52
【问题描述】:

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

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

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

【问题讨论】:

  • 那个问题不包括 Django,我已经看过了,它展示了如何从头开始编码,我怀疑这是正确的方法。
  • 我不好我会删除它
  • 我认为没有要删除的关键字,所有现有示例都显示了您编写的代码。

标签: django graphene-python graphene-django


【解决方案1】:

类似这样,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()

【讨论】:

  • django_model 字段的用途是什么?
  • 很好——它是我用来创建示例的代码遗留下来的。不需要,所以我从示例中删除。
  • 谢谢,现在竞争有意义了。
  • 我开始觉得GraphQL 适合Read 不适合Create/Update/Delete。甚至上传Files。我必须自己定制。 DRF 是 IMO 的好人
  • 我同意上传/下载文件。在stackoverflow.com/questions/49503756/… 上查看我的回答
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      通过Python + Graphene hackernews tutorial,我派生了以下用于删除链接对象的实现:

      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-01-31
        • 2020-05-30
        • 2020-08-13
        • 2021-04-09
        • 1970-01-01
        • 2017-07-26
        • 1970-01-01
        • 2023-01-09
        • 1970-01-01
        相关资源
        最近更新 更多