Created
August 27, 2018 08:04
-
-
Save Mhs-220/0b1cfefdff7e2c37c2a5973569c26384 to your computer and use it in GitHub Desktop.
Add order field to graphene django
This file contains hidden or 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
import graphene | |
from graphene_django.filter import DjangoFilterConnectionField | |
class CustomDjangoFilterConnectionField(DjangoFilterConnectionField): | |
@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 | |
# Whole class is just like source, we just need to add this three line | |
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, | |
info, | |
**args | |
) | |
# Then you shoud change your query node to something like this | |
class UserQuery(graphene.ObjectType): | |
retrieve_users = CustomDjangoFilterConnectionField( | |
UserNode, | |
orderBy = graphene.List(graphene.String) | |
) | |
# Use it like this: | |
# query { | |
# retrieveUsers(orderBy: ["-id", "last_name"]){ | |
# edges{ | |
# node{ | |
# what you want from users | |
# } | |
# } | |
# } | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment