[Question] - Single filter lookup object argument in queries instead of one for each filter field.
See original GitHub issueIm still really new to graphql in general so i dont know much about whether this is viable or not, but i know that if you define the filter fields on the node object as such,
filter_fields = {
'email' : [....],
'name' : [....]
}
They can be defined as single arguments on the query:
query ($email: String, ....) {
...
users(email: $email, name_Istartswith:....) {
...
}
}
However if you need to pass many filter arguments this can make the query string arguments really long. When we build up our graphql query in the front end, It would be convenient to just pass a single “filters” javascript object dynamically, so you dont have to pass each filter as an argument:
query ($filters: SomeNodeFilterType, ....) {
...
users(filters: $filters) {
...
}
}
Where filters object looks something like and is passed into the variables:
{
"filters": {
"email_Icontains": "someone@example.com"
"name_Istartswith": "someone",
//etc
}
}
I tried to do something along the lines in a custom extended filter connection field class, and basically taking the filtering arguments and creating dynamic class of object type where it’s fields are the filter lookup as the name and the type being their corresponding graphene field type, then merging “filters” into the kwargs that get passed to to_arguments
. I did not have any luck with this approach.
class CustomFilterConnectionField(DjangoFilterConnectionField):
...
@property
def args(self):
node_name = str(self.node_type)
class_name = "{node}Filter".format(node=node_name)
fields = {}
# extract the filtering args "{lookuptype: graphene field type}"
for k, v in self.filtering_args.items():
fields[k] = v.type
filter_kwargs = self.filtering_args
# if we have filtering args then, create a dynamic object type.
if len(fields):
# fails with "fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping."
dynamic_class = type(class_name, (ObjectType,), fields)
# cant set meta directly due to object base type preventing it, so this method fails as well.
# dynamic_class = type(class_name, (ObjectType,), {"_meta": {"fields": fields}})
merge_kwargs = {"filters": Argument(dynamic_class)}
filter_kwargs.update(merge_kwargs)
return to_arguments(self._base_args or OrderedDict(), filter_kwargs)
@args.setter
def args(self, args):
self._base_args = args
Perhaps im missing something or im taking the wrong approach to accomplish this but im curious as to whether this possible or not or if anyone has had any luck achieving something similar?
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
@jkimbo
Yes here’s what i ended up with:
Sorry for not getting back to you with this @surgiie . Did you manage to resolve your issue?