如何在单独的列表元素中返回graphql查询中的QuerySet列表?

时间:2019-07-04 07:51:03

标签: django graphql graphene-python graphene-django

我面临的问题是我有custom_filter的{​​{1}},它返回了MyModel的列表,例如

<QuerySet>

对象类型

[<QuerySet [<MyModel: xyz>]>, <QuerySet [<MyModel: xyz>, <MyModel: xyz>,<MyModel: xyz>]>]

查询

class MyModelNode(DjangoObjectType):
    class Meta:
        model=MyModel
        filter_fields=['id]
        interfaces = (graphene.relay.Node,)


如何处理查询集列表。 查询的graphql响应应提供一个以查询集为元素的列表。

class Query(graphene.ObjectType):
   my_model_items = graphene.List(MyModelNode)

   def resolve_my_model_items(self, info, **kwargs):
      my_model_filtered_items = MyModel.objects.custom_filter(kwargs)
      # my_model_filtered_items holds the list of querysets
      return my_model_filtered_items

如何在单独的列表元素中获取不同查询集的结果? [ { //These are from first <QuerySet> "myModelItems":[ { "fieldsIaskedFor":"response" } ] }, { //These are from second <QuerySet> "myModelItems":[ { "fieldsIaskedFor":"resp" }, { "fieldsIaskedFor":"resp" }, { "fieldsIaskedFor":"resp" }, ] }, ] 的数量是固定的。

要实现该目标我需要做什么?

1 个答案:

答案 0 :(得分:0)

这可以通过创建两个对象类型并将它们简单地嵌套在另一个对象中来实现。

第一个对象类型将是DjangoObjectType中的MyModel

class DjangoMyModelNode(DjangoObjectType):
    class Meta:
        model = MyModel
        filter_fields = ['id']
        interfaces = (graphene.relay.Node,)

第二种对象类型将是自定义ObjectType

class MyModelNode(graphene.ObjectType):
    my_model_items = graphene.List(DjangoMyModelNode)

    def resolve_my_model_items(self, info, **kwargs):
        return self

查询将保持不变

class Query(graphene.ObjectType):
    my_model_items = graphene.List(MyModelNode)

    def resolve_my_model_items(self, info, **kwargs):
        my_model_filtered_items = MyModel.objects.custom_filter(kwargs)
        # my_model_filtered_items holds the list of querysets
        return my_model_filtered_items

这将根据所需结果返回结果