Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def prefetch_and_select_related(query_set, info):
- if info.parent_type.name != 'Query':
- return query_set
- select_list, prefetch_list = [], []
- for ffield in info.field_asts:
- s, p = _prefetch_and_select_related(
- selections=ffield.selection_set.selections,
- prefix='',
- select_list=[],
- prefetch_list=[],
- )
- select_list += s
- prefetch_list += p
- print('Select', select_list)
- print('Prefetch', prefetch_list)
- if len(select_list) > 0:
- query_set = query_set.select_related(*select_list)
- if len(prefetch_list) > 0:
- query_set = query_set.prefetch_related(*prefetch_list)
- return query_set
- def _prefetch_and_select_related(selections, prefix, select_list, prefetch_list):
- for field in selections:
- if field.selection_set is not None:
- name = camelToSnake(field.name.value)
- if '_set' in name:
- select_list, prefetch_list = _prefetch_and_select_related(
- selections=field.selection_set.selections,
- prefix=concat(prefix, name),
- select_list=select_list,
- prefetch_list=prefetch_list + [concat(prefix, name)],
- )
- else:
- select_list, prefetch_list = _prefetch_and_select_related(
- selections=field.selection_set.selections,
- prefix=concat(prefix, name),
- select_list=select_list + [concat(prefix, name)],
- prefetch_list=prefetch_list,
- )
- return select_list, prefetch_list
- def concat(prefix, name):
- return '__'.join(filter(lambda str: len(str) > 0, [prefix, name]))
- class PrefetchMiddleware(object):
- def resolve(self, next, root, info, **args):
- if info.parent_type.name != 'Query':
- return next(root, info, **args)
- else:
- return Promise.resolve(prefetch_and_select_related(next(root, info, **args).value, info))
Add Comment
Please, Sign In to add comment