是否可以使用GraphQL查询单个请求的mptt树?

时间:2019-11-28 11:56:00

标签: python django recursion graphql

我可以使用序列化器使用Django REST查询MPTT整棵树。现在,我正在升级我的服务以支持GraphQL。但是我只能使用iGraphQL进行处理的唯一方法是提供最多的深度以获取树的最后一个子节点

这是我的DRF和查询树的常用技术 models.py

from mptt.models import MPTTModel

class Question(MPTTModel):
   answer = models.TextField(null=True, blank=True)
   parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

serializers.py

from rest_framework import serializers

from questions.models import Question


class QuestionTreeSerializer(serializers.ModelSerializer):
    class Meta:
       model = Question
       fields = [
          'id',
          'parent',
          'children',
       ]
    def get_fields(self):
        fields = super().get_fields()
        fields['children'] = QuestionTreeSerializer(many=True)
        return fields

这是我当前的GraphQL实现

from graphene import relay
from graphene_django import DjangoObjectType

from questions.models import Question


class QuestionType(DjangoObjectType):
    class Meta:
        model = Question
        interfaces = (relay.Node,)
        fields = [
            'id',
            'name',
            'children',
            'parent',
        ]


class QuestionConnection(relay.Connection):
    class Meta:
        node = QuestionType


class Query:
    questions = relay.ConnectionField(QuestionConnection)

    @staticmethod
    def resolve_questions(root, info, **kwargs):
        return Question.objects.all()

这是我当前的查询

query{
  questions{
    edges{
      node{
        id
        name
        children {
          edges {
            node {
              id
              name
              children {
                edges {
                  node {
                    id
                    children {
                        edges {
                            node {
                                id
                                }
                        }
                    }
                    }
                }
              }
            }
          }
        }
        parent {
          id
        }
      }
    }
  }
}

问题:
这是静态查询,无法将所有子项都包含在树中

解决方法:
我必须将嵌套查询添加到有效负载中最深的级别才能获取所有分支。这不是一个好习惯,但至少可以奏效

问题:
是否可以使用GraphQLdjango-mptt一样一次查询DRF树?

0 个答案:

没有答案