创建/删除/更新/删除(CRUD)突变通常返回相应的数据库模型实例作为突变的输出类型。但是对于非CRUD突变,我想定义特定于业务逻辑的突变输出类型。例如。返回列表元素的数量+无法在graphql类型和db模型之间一对一映射的ID列表。我该如何使用graphene-django
来做到这一点?
答案 0 :(得分:1)
要返回计数和元素列表时,可以创建一个自定义类型:
class ListWithCountType(graphene.Scalar):
@staticmethod
def serialize(some_argument):
# make computation here
count = ...
some_list = ...
return { "count": count, "list": some_list }
然后在您的突变中按如下方式使用它:
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)
添加到您的架构:
class Query(graphene.ObjectType):
my_mutation = MyMutation.Field()
应返回以下内容:
{
"data": {
"list_with_count": {
"count": <COUNT VALUE>,
"list": <SOME_LIST VALUE>
}
}
}
* PS:如果仅是输出,那么可以。但是,如果希望将此类型作为参数,则除了“ serialize”之外,还应该实现“ parse_literal”和“ parse_value”。
Here是一个与表单一起使用的自定义ErrorType的示例。
来自docs:
# 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()
在您的架构上:
import graphene
import cookbook.ingredients.schema
class Query(cookbook.ingredients.schema.Query, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query)
然后您可以查询:
query {
allCategories {
id
}
}
应返回以下内容:
{
"data": {
"allCategories": [
{
"id": "1",
},
{
"id": "2",
},
{
"id": "3",
},
{
"id": "4",
}
]
}
}