[英]GraphQL multiple queries in one request in Django
我使用 Django 和石墨烯來構建 API,但我想在一個查詢中組合兩個模型,模型的所有字段都相同。
示例schema.py
import graphene
from graphene_django import DjangoObjectType
from .models import Post, Post2
class PostType(DjangoObjectType):
class Meta:
model = Post
class Post2Type(DjangoObjectType):
class Meta:
model = Post2
class Query(graphene.ObjectType):
post = graphene.List(PostType)
post2 = graphene.List(Post2Type)
def resolve_post(self, info):
return Post.objects.all()
def resolve_post2(self, info):
return Post2.objects.all()
我得到這個回應:
{
"data": {
"post": [
{
"title": "post 1"
}
],
"post2": [
{
"title": "post test"
}
]
}
}
我想得到的是:
{
"data": {
"allPost": [
{
"title": "post 1"
},
{
"title": "post test"
}
}
}
您可以創建一個聯合類型列表(https://docs.graphene-python.org/en/latest/types/unions/#unions ),它應該給你你想要的:
class PostUnion(graphene.Union):
class Meta:
types = (PostType, Post2Type)
@classmethod
def resolve_type(cls, instance, info):
# This function tells Graphene what Graphene type the instance is
if isinstance(instance, Post):
return PostType
if isinstance(instance, Post2):
return Post2Type
return PostUnion.resolve_type(instance, info)
class Query(graphene.ObjectType):
all_posts = graphene.List(PostUnion)
def resolve_all_posts(self, info):
return list(Post.objects.all()) + list(Post2.objects.all())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.