Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django中一个请求中的GraphQL多个查询_Python_Django_Graphql_Graphene Django - Fatal编程技术网

Python Django中一个请求中的GraphQL多个查询

Python Django中一个请求中的GraphQL多个查询,python,django,graphql,graphene-django,Python,Django,Graphql,Graphene Django,我使用Django和graphene来构建API,但我想在一个查询中组合两个模型,模型的所有字段都是相同的 示例 schema.py import graphene from graphene_django import DjangoObjectType from .models import Post, Post2 class PostType(DjangoObjectType): class Meta: model = Post class Post2Type(D

我使用Django和graphene来构建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"
      }
  }
}

您可以创建联合类型()的列表,该列表应提供您想要的:

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())