使用graphene_django无法从GraphQL获取最后n个元素

时间:2019-02-21 05:31:10

标签: django django-rest-framework graphql graphene-python

我试图在现有的Django REST Framework中实现GraphQL。我使用了 graphene-django == 2.2.0

已成功实施。但是不能在请求查询中使用'last'关键字。我正在添加架构代码。

import graphene
from graphene_django.types import DjangoObjectType
from flowers.models import Flower


class FlowerType(DjangoObjectType):
    class Meta:
        model = Flower


class Query(graphene.ObjectType):
    flowers = graphene.List(FlowerType)

    def resolve_flowers(self, info, **kwargs):
        return Flower.objects.all()

查询

{
    flowers (last: 2){
        id
    }
}

结果

{
  "errors": [
    {
      "locations": [
        {
          "column": 12,
          "line": 2
        }
      ],
      "message": "Unknown argument \"last\" on field \"flowers\" of type \"Query\"."
    }
  ]
}

我必须修改Django项目中的代码吗?如何解决?

2 个答案:

答案 0 :(得分:0)

在您的GraphQL模式中。您需要具体说明接受最后一个参数并返回查​​询的查询。请指定鲜花的退还类型(以您的情况为准)

class Query(graphene.ObjectType):
  flowers = graphene.List(FlowerType, last=graphene.Int())

  def resolve_flowers(self, args, context, info):
    query = FlowerType.get_query(context)
    return query.get(args.get('last'))

Or

query($last: Int!): ReturnType

您可以将查询更改为此

query($flowerId: 2) {
    flowers (last: $flowerId){
        id
    }
}

答案 1 :(得分:0)

或者简单地使用中继,它已经提供了此过滤器。

class FlowerType(DjangoObjectType):
    class Meta:
        model = Flower
        interfaces = (graphene.relay.Node,)

class FlowerConnection(graphene.relay.Connection):
    class Meta:
        node = FlowerType

class Query(graphene.ObjectType):
    flowers = graphene.relay.ConnectionField(FlowerConnection)

    def resolve_flowers(self, info, **kwargs):
        return Flower.objects.all()