GraphQL несколько запросов в одном запросе в Django - PullRequest
1 голос
/ 27 марта 2020

Я использую Django с графеном для создания 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"
      }
  }
}

1 Ответ

1 голос
/ 02 апреля 2020

Вы можете создать список типа Union (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())
...