6.Fields领域
Graphene-Django provides some useful fields to help integrate Django with your GraphQL Schema.
Graphene-Django提供了一些有用的字段来帮助将Django与GraphQL模式集成。
DjangoListField Django列表字段
DjangoListField
allows you to define a list of DjangoObjectType‘s. By default it will resolve the default queryset of the Django model.
DjangoListField
允许您定义DjangoObjectType的列表。默认情况下,它将解析Django模型的默认queryset。
from graphene import ObjectType, Schema
from graphene_django import DjangoListField
class RecipeType(DjangoObjectType):
class Meta:
model = Recipe
fields = ("title", "instructions")
class Query(ObjectType):
recipes = DjangoListField(RecipeType)
schema = Schema(query=Query)
The above code results in the following schema definition:
上述模式定义中的结果如下:
schema {
query: Query
}
type Query {
recipes: [RecipeType!]
}
type RecipeType {
title: String!
instructions: String!
}
Custom resolvers 自定义冲突解决程序
If your DjangoObjectType
has defined a custom get_queryset method, when resolving a DjangoListField
it will be called with either the return of the field resolver (if one is defined) or the default queryset from the Django model.
如果您的djangObjectType
定义了一个自定义的get_queryset方法,则在解析DjangoListField
时,将通过返回字段解析程序(如果已定义)或Django模型中的默认queryset来调用该方法。
For example the following schema will only resolve recipes which have been published and have a title:
例如,以下模式将仅解析已发布并具有标题的配方:
from graphene import ObjectType, Schema
from graphene_django import DjangoListField
class RecipeType(DjangoObjectType):
class Meta:
model = Recipe
fields = ("title", "instructions")
@classmethod
def get_queryset(cls, queryset, info):
# Filter out recipes that have no title
# 过滤掉没有标题的食谱
return queryset.exclude(title__exact="")
class Query(ObjectType):
recipes = DjangoListField(RecipeType)
def resolve_recipes(parent, info):
# Only get recipes that have been published
# 只获取已经出版的食谱
return Recipe.objects.filter(published=True)
schema = Schema(query=Query)
DjangoConnectionField Django连接字段
TODO