更新时间:2023-12-01 15:04:52
您可以通过创建一个表示两个模型中的字段的类型来实现此目的.例如:
You can achieve this by creating a type which expresses fields from both models. For example:
import graphene
from graphene_django.types import DjangoObjectType
# hybrid type, expresses some characteristics of Member and Group
class UserGroupType(DjangoObjectType):
class Meta:
model = Membership
# date_joined is automatically derived from the membership
# instance, name and id are declared below.
fields = ('id', 'name', 'date_joined', )
id = graphene.ID()
name = graphene.String()
def resolve_id(value_obj, info):
return value_obj.group.pk
def resolve_name(value_obj, info):
return value_obj.group.name
class PersonType(DjangoObjectType):
class Meta:
model = Person
# id and name are automatically derived from the person
# instance, groups is declared below, overriding the
# normal model relationship.
fields = ('id', 'name', 'groups', )
groups = graphene.List(UserGroupType)
def resolve_groups(value_obj, info):
return value_obj.memberships
对于从Graphene的 ObjectType (其中 DjangoObjectType 来表示输出中的字段需要两件事:
For any type built from Graphene's ObjectType (which DjangoObjectType descends from), to express a field in output you need two things:
DjangoObjectType
评估您提供的模型以自动生成这些模型,并使用
DjangoObjectType
evaluates the model you provide it to generate these automatically and uses the fields attribute to let you customize what properties to reveal.
通过自定义 fields
,然后为要添加的内容添加手动prop/resolver,可以使类型返回您想要的任何内容.
By customizing fields
and then adding manual props/resolvers for what you want to add you can make the type return anything you want.
Note the resolvers don't receive self
as the first argument, but instead get a value object. The value object is the return value of your query resolver and is generally an instance of your model or an array of models that matched a filter, etc.