Sometimes we need to have a custom resolver function. In those cases, the field can't be auto optimized.
So we need to use gql_optimizer.resolver_hints decorator to indicate the optimizations.
If the resolver returns a model field, we can use the model_field argument:
import graphene
import graphene_django_optimizer as gql_optimizer
class ItemType(gql_optimizer.OptimizedDjangoObjectType):
product = graphene.Field('ProductType')
@gql_optimizer.resolver_hints(
model_field='product',
)
def resolve_product(root, info):
# check if user have permission for seeing the product
if info.context.user.is_anonymous():
return None
return root.product
This will automatically optimize any subfield of product.
Now, if the resolver uses related fields, you can use the select_related argument:
import graphene
import graphene_django_optimizer as gql_optimizer
class ItemType(gql_optimizer.OptimizedDjangoObjectType):
name = graphene.String()
@gql_optimizer.resolver_hints(
select_related=('product', 'shipping'),
only=('product__name', 'shipping__name'),
)
def resolve_name(root, info):
return '{} {}'.format(root.product.name, root.shipping.name)
Notice the usage of the type OptimizedDjangoObjectType, which enables
optimization of any single node queries.
Finally, if your field has an argument for filtering results,
you can use the prefetch_related argument with a function
that returns a Prefetch instance as the value.
Sometimes we need to have a custom non model fields. In those cases, the optimizer would not optimize with the Django .only() method.
So if we still want to optimize with the .only() method, we need to use disable_abort_only option:
class IngredientType(gql_optimizer.OptimizedDjangoObjectType):
calculated_calories = graphene.String()
class Meta:
model = Ingredient
def resolve_calculated_calories(root, info):
return get_calories_for_ingredient(root.id)
class Query(object):
all_ingredients = graphene.List(IngredientType)
def resolve_all_ingredients(root, info):
return gql_optimizer.query(Ingredient.objects.all(), info, disable_abort_only=True)