如何为使用石墨烯-django的突变定义自定义输出类型? [英] How can I define custom output types for mutations with graphene-django?
问题描述
创建/删除/更新/删除(CRUD)突变通常返回相应的数据库模型实例作为突变的输出类型.但是,对于非CRUD突变,我想定义特定于业务逻辑的突变输出类型.例如.返回列表元素的数量+不能在graphql类型和db模型之间一对一映射的ID列表.如何使用 graphene-django
实现此目标?
Create/remove/update/delete (CRUD) mutations usually return the corresponding database model instance as output type of the mutation. However for non-CRUD mutations I'd like to define business logic specific mutation output types. E.g. returning the count of list elements + a list of IDs which cannot be mapped 1-to-1 between graphql type and db models. How can I achieve this with graphene-django
?
推荐答案
与模型无关的列表
要返回计数和元素列表时,可以创建一个自定义类型:
List not related to Models
As you want to return both a count and a list of elements, you can create a custom type:
class ListWithCountType(graphene.Scalar):
@staticmethod
def serialize(some_argument):
# make computation here
count = ...
some_list = ...
return { "count": count, "list": some_list }
然后在您的突变中按如下方式使用它:
Then on your mutation you use it like this:
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".
*PS: if this is only an output, ok. But if you want this type to be an argument, you should also implement "parse_literal" and "parse_value", besides the "serialize".
此处是一个与表单一起使用的自定义ErrorType的示例.
Here is an example with a custom ErrorType used with forms.
来自在您的架构上:
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",
}
]
}
}
这是一个带有用户模型的示例.
这篇关于如何为使用石墨烯-django的突变定义自定义输出类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!