简体   繁体   English

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

[英]GraphQL multiple queries in one request in Django

Im using Django with graphene to build an API but i want to combine two models in one query, all the fields of the models are the same.我使用 Django 和石墨烯来构建 API,但我想在一个查询中组合两个模型,模型的所有字段都相同。

Example schema.py示例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()

I get this response:我得到这个回应:

{
  "data": {
    "post": [
      {
        "title": "post 1"
      }
    ],
    "post2": [
      {
        "title": "post test"
      }
    ]
  }
}

What i want to get is:我想得到的是:

{
  "data": {
    "allPost": [
      {
        "title": "post 1"
      },
      {
        "title": "post test"
      }
  }
}

You can create a list of a Union type (https://docs.graphene-python.org/en/latest/types/unions/#unions ) which should give you what you want:您可以创建一个联合类型列表(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM