barseghyanartur / graphene-elastic

Graphene Elasticsearch/OpenSearch (DSL) integration
https://pypi.org/project/graphene-elastic/
71 stars 17 forks source link

Possibility to use the request object in Filter backends #53

Closed andrijan closed 3 years ago

andrijan commented 3 years ago

Hey, just found this project, looks really good!

While testing this out on my project (Which currently uses django-elasticsearch-dsl-drf) I wanted to pre-filter the queryset by only selecting the documents the user has access to. But to do that I would need the request object.

The filter backend in the django-elasticsearch-dsl-drf I currently use (and trying to replicate) looks like this:

def filter_queryset(self, request, queryset, view):
    return queryset.filter(
        E_Q(
            'nested',
            path='followers',
            query=E_Q(
                'match',
                followers__id=request.user.id
            )
        ) | E_Q(
            'nested',
            path='job.followers',
            query=E_Q('match', job__followers__id=request.user.id)
        )
    )

Any idea how I could solve it with your project?

barseghyanartur commented 3 years ago

@andrijan:

See the updated example project (the very minimal configuration to have authentication checks working):

  1. Create a Django user

./scripts/run_django.sh createsuperuser

  1. Run Elasticsearch

docker-compose up

  1. Add some data to the Elasticsearch

./scripts/populate_elasticsearch_data.sh

  1. Run the example project:

./scripts/run_django.sh runserver

  1. Go to http://localhost:8000/admin/ and enter your credentials

  2. Go to http://localhost:8000/graphql and type in the following query:

query PostsQuery {
      postDocumentsForUser {
        edges {
          node {
            id
            title
            userId
          }
        }
      }
    }

P. S.

If you have more questions regarding this implementation, take an initiative to dive deeper into the subject (Django/GraphQL/Elasticsearch).