MCPcopy
hub / github.com/tortoise/tortoise-orm / prefetch_related

Method prefetch_related

tortoise/queryset.py:1016–1043  ·  view source on GitHub ↗

Like ``.fetch_related()`` on instance, but works on all objects in QuerySet. :raises FieldError: If the field to prefetch on is not a relation, or not found.

(self, *args: str | Prefetch)

Source from the content-addressed store, hash-verified

1014 return self
1015
1016 def prefetch_related(self, *args: str | Prefetch) -> QuerySet[MODEL]:
1017 """
1018 Like ``.fetch_related()`` on instance, but works on all objects in QuerySet.
1019
1020 :raises FieldError: If the field to prefetch on is not a relation, or not found.
1021 """
1022 queryset = self._clone()
1023 queryset._prefetch_map = {}
1024
1025 for relation in args:
1026 if isinstance(relation, Prefetch):
1027 relation.resolve_for_queryset(queryset)
1028 continue
1029
1030 first_level_field, __, forwarded_prefetch = relation.partition("__")
1031 if first_level_field not in self.model._meta.fetch_fields:
1032 if first_level_field in self.model._meta.fields:
1033 raise FieldError(
1034 f"Field {first_level_field} on {self.model._meta.full_name} is not a relation"
1035 )
1036 raise FieldError(
1037 f"Relation {first_level_field} for {self.model._meta.full_name} not found"
1038 )
1039 if first_level_field not in queryset._prefetch_map.keys():
1040 queryset._prefetch_map[first_level_field] = set()
1041 if forwarded_prefetch:
1042 queryset._prefetch_map[first_level_field].add(forwarded_prefetch)
1043 return queryset
1044
1045 async def explain(self) -> Any:
1046 """Fetch and return information about the query execution plan.

Callers 15

from_queryset_singleMethod · 0.45
from_querysetMethod · 0.45
from_querysetMethod · 0.45
test_prefetchFunction · 0.45
test_prefetch_objectFunction · 0.45
test_prefetch_m2mFunction · 0.45
test_prefetch_o2oFunction · 0.45
test_prefetch_nestedFunction · 0.45

Calls 5

_cloneMethod · 0.95
FieldErrorClass · 0.90
resolve_for_querysetMethod · 0.80
keysMethod · 0.80
addMethod · 0.80

Tested by 15

test_prefetchFunction · 0.36
test_prefetch_objectFunction · 0.36
test_prefetch_m2mFunction · 0.36
test_prefetch_o2oFunction · 0.36
test_prefetch_nestedFunction · 0.36
test_prefetch_bad_keyFunction · 0.36
test_prefetch_m2m_filterFunction · 0.36