tfoxy / graphene-django-optimizer

Optimize database access inside graphene queries

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Optimize retrieving a single object

stickperson opened this issue · comments

I'm following the graphene-django tutorial and got up to retrieving a single object. The README here does not mention how optimization would work here. gql_optimizer.query expects a queryset. As a workaround, I'm using:

      def resolve_category(self, info, **kwargs):
          id = kwargs.get('id')
          name = kwargs.get('name')

          if id is not None:
              return gql_optimizer.query(Category.objects.filter(pk=id), info).get()

          if name is not None:
              return gql_optimizer.query(Category.objects.filter(name=name), info).get()

          return None

Is this the recommended approach?

Interested to know the proposed solution here as well, this seems like it should work ok. Not sure if it could be supported, but obviously preferred developer experience would likely be:

gql_optimizer.query(Category.objects.get(name=name), info)

which currently raises 'Category' object has no attribute 'select_related'

That's because .get() returns an instance instead of a queryset. You can do gql_optimizer.query(Category.objects.select_related(...).get(name=name), info)

@stickperson Yep, makes sense, I am using your workaround for now 👍

Yes, the first post is the recommended approach. It's been a long time since I used Django, but from what I remember, when using .get you would lose the prefetch_related optimizations.