MCPcopy
hub / github.com/django/django / __getitem__

Method __getitem__

django/db/models/query.py:451–486  ·  view source on GitHub ↗

Retrieve an item or slice from the set of results.

(self, k)

Source from the content-addressed store, hash-verified

449 return bool(self._result_cache)
450
451 def __getitem__(self, k):
452 """Retrieve an item or slice from the set of results."""
453 if not isinstance(k, (int, slice)):
454 raise TypeError(
455 "QuerySet indices must be integers or slices, not %s."
456 % type(k).__name__
457 )
458 if (isinstance(k, int) and k < 0) or (
459 isinstance(k, slice)
460 and (
461 (k.start is not None and k.start < 0)
462 or (k.stop is not None and k.stop < 0)
463 )
464 ):
465 raise ValueError("Negative indexing is not supported.")
466
467 if self._result_cache is not None:
468 return self._result_cache[k]
469
470 if isinstance(k, slice):
471 qs = self._chain()
472 if k.start is not None:
473 start = int(k.start)
474 else:
475 start = None
476 if k.stop is not None:
477 stop = int(k.stop)
478 else:
479 stop = None
480 qs.query.set_limits(start, stop)
481 return list(qs)[:: k.step] if k.step else qs
482
483 qs = self._chain()
484 qs.query.set_limits(k, k + 1)
485 qs._fetch_all()
486 return qs._result_cache[0]
487
488 def __class_getitem__(cls, *args, **kwargs):
489 return cls

Callers

nothing calls this directly

Calls 3

_chainMethod · 0.95
set_limitsMethod · 0.80
_fetch_allMethod · 0.45

Tested by

no test coverage detected