Django Graphene中继order_by(OrderingFilter)

时间:2019-08-13 13:11:32

标签: django graphene-python graphene-django

我有一个带有Relay和过滤器的Graphene接口。它工作得很好,但我想添加order_by选项。我的对象看起来像:

    class FooGQLType(DjangoObjectType):
    class Meta:
        model = Foo
        exclude_fields = ('internal_id',)
        interfaces = (graphene.relay.Node,)
        filter_fields = {
            "id": ["exact"],
            "code": ["exact", "icontains"],
        }
        connection_class = ExtendedConnection

class Query(graphene.ObjectType):
    foo = DjangoFilterConnectionField(FooGQLType)

ExtendedConnection不应该相关,但是:

class ExtendedConnection(graphene.Connection):
    class Meta:
        abstract = True

    total_count = graphene.Int()

    def resolve_total_count(root, info, **kwargs):
        return root.length

这使我可以像foo(code_Icontains:"bar")一样进行查询。 根据{{​​3}},我应该为此在FilterSet中使用OrderingFilter。我觉得这有点烦人,因为过滤器应该是自动的,但是如果我这样做的话:

    class FooGQLFilter(FilterSet):
    class Meta:
        model = Foo

    order_by = OrderingFilter(
        fields=(
            ('code', 'code'),
            ('lastName', 'last_name'),
            ('otherNames', 'other_names'),
        )
    )

我收到需要提供fieldsexclude的错误消息:

AssertionError: Setting 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated since 0.15.0 and is now disallowed. Add an explicit 'Meta.fields' or 'Meta.exclude' to the FooGQLFilter class.

因此,如果我添加一个fields = []使其静音,则它将编译。 但是,当我在以下位置使用它时:

foo = DjangoFilterConnectionField(FooGQLType, filterset_class=FooGQLFilter)

我的常规过滤器(例如code_Icontains)消失了。我可以在那儿再次添加它们,但这很愚蠢。快速查看源代码,看起来Relay或django-filters已经创建了一个FilterSet类(很有意义),用这种方式覆盖它显然是一个糟糕的主意。

如何在Graphene Relay过滤的对象上添加orderBy过滤器?我觉得这应该很简单,但是我正在努力弄清楚。

我还看到了用DjangoFilterConnectionField子类化connection_resolver的示例,该示例以某种方式注入了order_by,但告诉我没有orderBy参数。

3 个答案:

答案 0 :(得分:4)

Eric的解决方案不适用于当前的graphene-django版本(2.9.1)或更高版本的graphene-django 2.6.0版本。

DjangoFilterConnectionField方法在2.7.0版本中进行了更改。 有关更多详细信息,您可以检查更改日志here

使用Eric的解决方案,它将产生错误, connection_resolver() missing 1 required positional argument: 'info’

所以我已经修改了解决方案,并且效果很好。

from graphene_django.filter import DjangoFilterConnectionField
from graphene.utils.str_converters import to_snake_case


class OrderedDjangoFilterConnectionField(DjangoFilterConnectionField):

    @classmethod
    def resolve_queryset(
        cls, connection, iterable, info, args, filtering_args, filterset_class
    ):
        qs = super(DjangoFilterConnectionField, cls).resolve_queryset(
            connection, iterable, info, args
        )
        filter_kwargs = {k: v for k, v in args.items() if k in filtering_args}
        qs = filterset_class(data=filter_kwargs, queryset=qs, request=info.context).qs

        order = args.get('orderBy', None)
        if order:
            if type(order) is str:
                snake_order = to_snake_case(order)
            else:
                snake_order = [to_snake_case(o) for o in order]
            qs = qs.order_by(*snake_order)
        return qs

答案 1 :(得分:1)

我已经针对这个主题改编了a GitHub issue的解决方案:

from graphene_django.filter import DjangoFilterConnectionField
from graphene.utils.str_converters import to_snake_case


class OrderedDjangoFilterConnectionField(DjangoFilterConnectionField):
    """
    Adapted from https://github.com/graphql-python/graphene/issues/251
    Substituting:
    `claims = DjangoFilterConnectionField(ClaimsGraphQLType)`
    with:
    ```
    claims = OrderedDjangoFilterConnectionField(ClaimsGraphQLType,
        orderBy=graphene.List(of_type=graphene.String))
    ```
    """
    @classmethod
    def connection_resolver(cls, resolver, connection, default_manager, max_limit,
                            enforce_first_or_last, filterset_class, filtering_args,
                            root, info, **args):
        filter_kwargs = {k: v for k, v in args.items() if k in filtering_args}
        qs = filterset_class(
            data=filter_kwargs,
            queryset=default_manager.get_queryset(),
            request=info.context
        ).qs
        order = args.get('orderBy', None)
        if order:
            if type(order) is str:
                snake_order = to_snake_case(order)
            else:
                snake_order = [to_snake_case(o) for o in order]
            qs = qs.order_by(*snake_order)
        return super(DjangoFilterConnectionField, cls).connection_resolver(
            resolver,
            connection,
            qs,
            max_limit,
            enforce_first_or_last,
            root,
            info,
            **args
        )

要使用它,只需修改以下查询:

claims = DjangoFilterConnectionField(ClaimsGraphQLType)

claims = OrderedDjangoFilterConnectionField(ClaimsGraphQLType,
        orderBy=graphene.List(of_type=graphene.String))

然后您可以查询:

{ claims(status: 2, orderBy: "-id") { id } }

{ claims(status: 2, orderBy: ["creationDate", "lastName"]) { id } }

答案 2 :(得分:0)

嘿,我相信我有一个简单易行的答案来处理 orderBy,尤其是作为石墨烯中的列表。我回答的原因不是因为我相信我有最聪明的解决方案,我只是想知道如果我在不知不觉中造成伤害有什么区别。我实际上不了解 graphene_django 中的连接内容,因此我从观看有关 GraphQL 中排序对象的讨论中获得启发,采取了不同的路线。

https://www.youtube.com/watch?v=dDxUu-K2qdE

首先使用您的 FooType,我已将字段添加为枚举

class FooGQLType(DjangoObjectType):
    class Meta:
        model = Foo

class FooFields(graphene.Enum):
    CODE = "code"
    LAST_NAME = "last_name"
    OTHER_NAMES = "other_names"

class Directions(graphene.Enum):
    ASC = "asc"
    DESC = "desc"

然后输入以在 Query

中传递它们
class FooOrderByInput(graphene.InputObjectType):
    order_by = FooFields()
    direction = Directions()

我不确定您要过滤的内容,但由于问题主要是关于 order_by,所以我暂时假设它是一个随机字符串。我觉得有一种方法可以发出这一行 db 请求,但我不确定如何。

ORDER_BY = 'order_by'
DIRECTION = 'direction'

class Query(graphene.ObjectType):
    foo = graphene.Field(FooGQLType, input=graphene.List(FooOrderByInput), filter_opt=graphene.String())

    def resolve_foo(self, info, input):
        qs = Foo.objects.filter(filter_opt=filter_opt)
        for obj in input:
            order_by = obj.get(ORDER_BY)
            direction = "-" if obj.get(DIRECTION) == Directions.DESC else ""
            qs = qs.order_by(f"{direction}{order_by}")

        return  qs

这方面最好的事情(无论如何对我来说)是它允许对多个字段进行查询,例如

query ($input: [FooOrderByInput]) {
  foo (input: $input) {
    id
    code
    lastName
    otherNames
  }
}

VARIABLES
{
    "input": [
        {
            "orderBy": "LAST_NAME",
            "direction": "DESC"
        },
        {
            "orderBy": "CODE",
            "direction": "ASC"
        }
    ]
}

而且除了那些拼写正确的关键字外,它也不允许任何其他内容。它也不必处理camelCase到snake_case。

如果有更好的解决方案或者我的很烂,请告诉我。我很高兴这似乎已经解决了!