The default queryset, that builds queries and handles a set of results returned from a query. Wraps a MongoDB cursor, providing :class:`~mongoengine.Document` objects as the results.
| 24 | |
| 25 | |
| 26 | class QuerySet(BaseQuerySet): |
| 27 | """The default queryset, that builds queries and handles a set of results |
| 28 | returned from a query. |
| 29 | |
| 30 | Wraps a MongoDB cursor, providing :class:`~mongoengine.Document` objects as |
| 31 | the results. |
| 32 | """ |
| 33 | |
| 34 | _has_more = True |
| 35 | _len = None |
| 36 | _result_cache = None |
| 37 | |
| 38 | def __iter__(self): |
| 39 | """Iteration utilises a results cache which iterates the cursor |
| 40 | in batches of ``ITER_CHUNK_SIZE``. |
| 41 | |
| 42 | If ``self._has_more`` the cursor hasn't been exhausted so cache then |
| 43 | batch. Otherwise iterate the result_cache. |
| 44 | """ |
| 45 | self._iter = True |
| 46 | |
| 47 | if self._has_more: |
| 48 | return self._iter_results() |
| 49 | |
| 50 | # iterating over the cache. |
| 51 | return iter(self._result_cache) |
| 52 | |
| 53 | def __len__(self): |
| 54 | """Since __len__ is called quite frequently (for example, as part of |
| 55 | list(qs)), we populate the result cache and cache the length. |
| 56 | """ |
| 57 | if self._len is not None: |
| 58 | return self._len |
| 59 | |
| 60 | # Populate the result cache with *all* of the docs in the cursor |
| 61 | if self._has_more: |
| 62 | list(self._iter_results()) |
| 63 | |
| 64 | # Cache the length of the complete result cache and return it |
| 65 | self._len = len(self._result_cache) |
| 66 | return self._len |
| 67 | |
| 68 | def __repr__(self): |
| 69 | """Provide a string representation of the QuerySet""" |
| 70 | if self._iter: |
| 71 | return ".. queryset mid-iteration .." |
| 72 | |
| 73 | self._populate_cache() |
| 74 | data = self._result_cache[: REPR_OUTPUT_SIZE + 1] |
| 75 | if len(data) > REPR_OUTPUT_SIZE: |
| 76 | data[-1] = "...(remaining elements truncated)..." |
| 77 | return repr(data) |
| 78 | |
| 79 | def _iter_results(self): |
| 80 | """A generator for iterating over the result cache. |
| 81 | |
| 82 | Also populates the cache if there are more possible results to |
| 83 | yield. Raises StopIteration when there are no more results. |