Skip to content

Instantly share code, notes, and snippets.

@matutter
Created February 6, 2020 04:10
Show Gist options
  • Save matutter/80e48ad9c6974abd228fc0b5ea5bc0b3 to your computer and use it in GitHub Desktop.
Save matutter/80e48ad9c6974abd228fc0b5ea5bc0b3 to your computer and use it in GitHub Desktop.
Example on adding filtering to connection fields.
class RoleInput(graphene.InputObjectType):
role = String()
class FilteredConnectionField(SQLAlchemyConnectionField):
def __init__(self, type, input_type, *args, **kwargs):
fields = {name: field.type() for name, field in input_type._meta.fields.items()}
kwargs.update(fields)
super().__init__(type, *args, **kwargs)
@classmethod
def get_query(cls, model, info, sort=None, **args):
query = super().get_query(model, info, sort=sort, **args)
omitted = ('first', 'last', 'hasPreviousPage', 'hasNextPage', 'startCursor', 'endCursor')
for name, val in args.items():
if name in omitted: continue
col = getattr(model, name, None)
if col:
query = query.filter(col == val)
return query
class Query(graphene.ObjectType):
users = FilteredConnectionField(Users, RoleInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment