-
-
Save ulkoart/c324ca54e988849d89a905afa0bdcc27 to your computer and use it in GitHub Desktop.
Django graphene orderBy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from graphene import relay, String, List | |
from graphene_django.filter import DjangoFilterConnectionField | |
from graphene_django.fields import DjangoConnectionField | |
from app.models import Model | |
class Object(DjangoObjectType): | |
class Meta: | |
model = Model | |
interfaces = (relay.Node,) | |
class OrderedDjangoFilterConnectionField(DjangoFilterConnectionField): | |
@classmethod | |
def connection_resolver(cls, resolver, connection, default_manager, max_limit, | |
enforce_first_or_last, filterset_class, filtering_args, | |
root, args, context, info): | |
filter_kwargs = {k: v for k, v in args.items() if k in filtering_args} | |
qs = default_manager.get_queryset() | |
qs = filterset_class(data=filter_kwargs, queryset=qs).qs | |
order = args.get('orderBy', None) | |
if order: | |
qs = qs.order_by(*order) | |
return super(DjangoFilterConnectionField, cls).connection_resolver( | |
resolver, | |
connection, | |
qs, | |
max_limit, | |
enforce_first_or_last, | |
root, | |
args, | |
context, | |
info | |
) | |
class Query(graphene.ObjectType): | |
''' | |
query{ | |
objects(orderBy: ['field1', '-field2']){ | |
... | |
} | |
} | |
''' | |
objects = OrderedDjangoFilterConnectionField(Object, orderBy=List(of_type=String)) | |
schema = graphene.Schema(query=Query) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment