Search code examples
djangographqlgraphene-python

Django Graphene filter Foreign Model


I need to filter the object my request on the back-end base on permissions.

For the following query :

query {
  foos {
    id
    name
    barSet {
      id
      name
    }
  }
}

There are permissions on foo and bar and I need to only return some foo and some bars.

I know that I can use field lookups for foos

class FooType(DjangoObjectType):
  class Meta:
    model = Foo

class BarType(DjangoObjectType):
  class Meta:
    model = Bar

class Query(object):
  foos = graphene.List(FooType)

  def resolve_foos(self, info, **kwargs):
    # id_list = some code to create a list of ids of possible foos

    return Foo.objects.filter(id__in=id_list)

Say I have a list of possible bars, how can I do the same to filter on bar when requested by a graphql query ?


Solution

  • Inside FooType you need to create a custom resolver for the bar field where you can apply permission filtering. For example, assuming a manager method on Bar called filter_by_user:

    class FooType(DjangoObjectType):
      bars = graphene.List(BarType)
    
      class Meta:
        model = Foo
    
      def resolve_bars(self, info):
          # do something to filter Bars by permissions
          return self.bar_set.filter_by_user(info.context.user)
    

    Also, in Bar Meta, you might need to add exclude_fields for bar_set field if it's added automatically.