Graphene-Django的docs非常说明了如何创建和更新对象。但是如何删除呢?我可以想象查询看起来像
mutation mut{
deleteUser(id: 1){
user{
username
email
}
error
}
}
但是我怀疑正确的方法是从头开始编写后端代码。
答案 0 :(得分:3)
类似这样的情况,其中UsersMutations
是您的架构的一部分:
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()
答案 1 :(得分:2)
这是一个小小的模型变异,您可以基于中继ClientIDMutation和graphene-django的SerializerMutation添加到您的项目中。我觉得这样或类似的东西应该是石墨烯-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。
答案 2 :(得分:0)
通过Python + Graphene hackernews教程[1],我导出了以下用于删除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: %s:%s:%s" % (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()
[1] https://www.howtographql.com/graphql-python/3-mutations/
答案 3 :(得分:0)
我为简单的模型变异制作了这个库:https://github.com/topletal/django-model-mutations,您可以在其中的示例中看到如何删除用户
class UserDeleteMutation(mutations.DeleteModelMutation):
class Meta:
model = User