Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Django graphene orderBy
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