thi*_*ybk 8 python django graphql graphql-mutation graphene-django
创建/删除/更新/删除(CRUD)突变通常返回相应的数据库模型实例作为突变的输出类型。然而,对于非 CRUD 突变,我想定义业务逻辑特定的突变输出类型。例如,返回列表元素的计数 + 不能在 graphql 类型和数据库模型之间一对一映射的 ID 列表。我怎样才能做到这一点graphene-django?
当您想要返回元素的计数和列表时,您可以创建自定义类型:
class ListWithCountType(graphene.Scalar):
@staticmethod
def serialize(some_argument):
# make computation here
count = ...
some_list = ...
return { "count": count, "list": some_list }
Run Code Online (Sandbox Code Playgroud)
然后在你的突变中你可以像这样使用它:
class MyMutation(graphene.Mutation):
list_with_count = graphene.Field(ListWithCountType)
@classmethod
def mutate(cls, root, info, **kwargs):
some_argument = kwargs.pop("some_argument")
return cls(list_with_count=some_argument)
Run Code Online (Sandbox Code Playgroud)
添加到您的架构:
class Query(graphene.ObjectType):
my_mutation = MyMutation.Field()
Run Code Online (Sandbox Code Playgroud)
应该返回类似:
{
"data": {
"list_with_count": {
"count": <COUNT VALUE>,
"list": <SOME_LIST VALUE>
}
}
}
Run Code Online (Sandbox Code Playgroud)
*PS:如果这只是一个输出,那么可以。但如果你希望这种类型作为参数,除了“serialize”之外,你还应该实现“parse_literal”和“parse_value”。
以下是与表单一起使用的自定义 ErrorType 的示例。
来自文档:
{
"data": {
"list_with_count": {
"count": <COUNT VALUE>,
"list": <SOME_LIST VALUE>
}
}
}
Run Code Online (Sandbox Code Playgroud)
在你的架构上:
# cookbook/ingredients/schema.py
import graphene
from graphene_django.types import DjangoObjectType
from cookbook.ingredients.models import Category
class CategoryType(DjangoObjectType):
class Meta:
model = Category
class Query(object):
all_categories = graphene.List(CategoryType)
def resolve_all_categories(self, info, **kwargs):
return Category.objects.all()
Run Code Online (Sandbox Code Playgroud)
然后你可以这样查询:
query {
allCategories {
id
}
}
Run Code Online (Sandbox Code Playgroud)
应该返回类似:
{
"data": {
"allCategories": [
{
"id": "1",
},
{
"id": "2",
},
{
"id": "3",
},
{
"id": "4",
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个用户模型的例子。