tfoxy / graphene-django-optimizer

Optimize database access inside graphene queries
MIT License
427 stars 86 forks source link

Resolvers that uses `.get` instead of `.filter` (i.e. returning `Model`, rather than `QuerySet` instance) on `Query`. #61

Open cansin opened 3 years ago

cansin commented 3 years ago

We are trying to get graphene-django-optimizer to work with our setup. Most of our queries start from a query { me { ... } } root. As such the implementation of the Query is:

class Query(graphene.ObjectType):
    me = graphene.Field(UserNode)

    @classmethod
    def resolve_me(cls, root, info):
        user = info.context.user
        if not user.is_authenticated:
            raise Exception("Authentication credentials were not provided")
        return user

or another example:

class Query(graphene.ObjectType):
    category = graphene.Field(CategoryNode, slug=graphene.String(required=True))

    @classmethod
    def resolve_category(cls, root, info, slug):
        return CategoryDefinition.objects.get(slug=slug)

We are not able to figure out how to get the subtree of such an entry point to optimize. Simply extending UserNode from OptimizedDjangoObjectType does not make any difference in the queries being run. Any idea on how we could utilize graphene-django-optimizer?

wodCZ commented 3 years ago
import graphene_django_optimizer as gql_optimizer

class Query(graphene.ObjectType):
    category = graphene.Field(CategoryNode, slug=graphene.String(required=True))

    @classmethod
    def resolve_category(cls, root, info, slug):
        return gql_optimizer.query(CategoryDefinition.objects.get_queryset().filter(slug=slug), info).first()

You should wrap the queryset in the query method, then call get (or first, I believe get didn't work as expected) on the result.

(Also see related discussion in https://github.com/tfoxy/graphene-django-optimizer/issues/46)