Return a document instance corresponding to a given index if the key is an integer. If the key is a slice, translate its bounds into a skip and a limit, and return a cloned queryset with that skip/limit applied. For example: >>> User.objects[0] <User: User ob
(self, key)
| 163 | # self._cursor |
| 164 | |
| 165 | def __getitem__(self, key): |
| 166 | """Return a document instance corresponding to a given index if |
| 167 | the key is an integer. If the key is a slice, translate its |
| 168 | bounds into a skip and a limit, and return a cloned queryset |
| 169 | with that skip/limit applied. For example: |
| 170 | |
| 171 | >>> User.objects[0] |
| 172 | <User: User object> |
| 173 | >>> User.objects[1:3] |
| 174 | [<User: User object>, <User: User object>] |
| 175 | """ |
| 176 | queryset = self.clone() |
| 177 | queryset._empty = False |
| 178 | |
| 179 | # Handle a slice |
| 180 | if isinstance(key, slice): |
| 181 | queryset._cursor_obj = queryset._cursor[key] |
| 182 | queryset._skip, queryset._limit = key.start, key.stop |
| 183 | if key.start and key.stop: |
| 184 | queryset._limit = key.stop - key.start |
| 185 | if queryset._limit == 0: |
| 186 | queryset._empty = True |
| 187 | |
| 188 | # Allow further QuerySet modifications to be performed |
| 189 | return queryset |
| 190 | |
| 191 | # Handle an index |
| 192 | elif isinstance(key, int): |
| 193 | if queryset._scalar: |
| 194 | return queryset._get_scalar( |
| 195 | queryset._document._from_son( |
| 196 | queryset._cursor[key], |
| 197 | _auto_dereference=self._auto_dereference, |
| 198 | ) |
| 199 | ) |
| 200 | |
| 201 | if queryset._as_pymongo: |
| 202 | return queryset._cursor[key] |
| 203 | |
| 204 | return queryset._document._from_son( |
| 205 | queryset._cursor[key], |
| 206 | _auto_dereference=self._auto_dereference, |
| 207 | ) |
| 208 | |
| 209 | raise TypeError("Provide a slice or an integer index") |
| 210 | |
| 211 | def __iter__(self): |
| 212 | raise NotImplementedError |