Graphene-django: [Question] - Single filter lookup object argument in queries instead of one for each filter field.

Created on 25 Jul 2019  路  5Comments  路  Source: graphql-python/graphene-django

Im 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": "[email protected]"
         "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?

Most helpful comment

@jkimbo

Yes here's what i ended up with:

    @property
    def args(self):
        node_name = str(self.node_type)
        class_name = "{node}Filter".format(node=node_name)
        fields = {}

        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):
            dynamic_class = type(class_name, (InputObjectType,), fields)

            filter_kwargs.update({"filters": Argument(dynamic_class)})

        return to_arguments(self._base_args or OrderedDict(), filter_kwargs)

    @args.setter
    def args(self, args):
        self._base_args = args

All 5 comments

@surgiie unfortunately this isn't a feature thats available in graphene-django currently although it sounds like a useful one! The approach you've taken to work around it seems like the right one though. What issues were you having with it?

@jkimbo

In theory i assumed the approach i took would work as well, but i keep getting this error when i tried creating the object type class dynamically dynamic_class = type(class_name, (ObjectType,), fields) :

 "fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping."

I also tried setting the fields in meta as another approach:

dynamic_class = type(class_name, (ObjectType,), {"_meta": {"fields": fields}}) but that fails because the base type from the graphene core prevents you from setting the meta directly:

https://github.com/graphql-python/graphene/blob/master/graphene/types/base.py#L40

I was not sure what other approach to take without really getting into extending the core library which i would like to avoid. Any suggestions?

@jkimbo Just giving you another try on my comment above.

Sorry for not getting back to you with this @surgiie . Did you manage to resolve your issue?

@jkimbo

Yes here's what i ended up with:

    @property
    def args(self):
        node_name = str(self.node_type)
        class_name = "{node}Filter".format(node=node_name)
        fields = {}

        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):
            dynamic_class = type(class_name, (InputObjectType,), fields)

            filter_kwargs.update({"filters": Argument(dynamic_class)})

        return to_arguments(self._base_args or OrderedDict(), filter_kwargs)

    @args.setter
    def args(self, args):
        self._base_args = args

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mraak picture mraak  路  3Comments

MythicManiac picture MythicManiac  路  3Comments

Eraldo picture Eraldo  路  3Comments

licx picture licx  路  3Comments

amiyatulu picture amiyatulu  路  3Comments