gpt4 book ai didi

python - Django 中一个请求中的 GraphQL 多个查询

转载 作者:行者123 更新时间:2023-12-04 10:20:25 25 4
gpt4 key购买 nike

我使用 Django 和 Graphite 烯来构建 API,但我想在一个查询中组合两个模型,模型的所有字段都相同。

示例
模式.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())

关于python - Django 中一个请求中的 GraphQL 多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60891084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com