@@ -158,44 +158,49 @@ def __setstate__(self, obj_dict):
158158 # self._cursor
159159
160160 def __getitem__ (self , key ):
161- """Support skip and limit using getitem and slicing syntax."""
161+ """Return a document instance corresponding to a given index if
162+ the key is an integer. If the key is a slice, translate its
163+ bounds into a skip and a limit, and return a cloned queryset
164+ with that skip/limit applied. For example:
165+
166+ >>> User.objects[0]
167+ <User: User object>
168+ >>> User.objects[1:3]
169+ [<User: User object>, <User: User object>]
170+ """
162171 queryset = self .clone ()
163172
164- # Slice provided
173+ # Handle a slice
165174 if isinstance (key , slice ):
166- try :
167- queryset ._cursor_obj = queryset ._cursor [key ]
168- queryset ._skip , queryset ._limit = key .start , key .stop
169- if key .start and key .stop :
170- queryset ._limit = key .stop - key .start
171- except IndexError as err :
172- # PyMongo raises an error if key.start == key.stop, catch it,
173- # bin it, kill it.
174- start = key .start or 0
175- if start >= 0 and key .stop >= 0 and key .step is None :
176- if start == key .stop :
177- queryset .limit (0 )
178- queryset ._skip = key .start
179- queryset ._limit = key .stop - start
180- return queryset
181- raise err
175+ queryset ._cursor_obj = queryset ._cursor [key ]
176+ queryset ._skip , queryset ._limit = key .start , key .stop
177+ if key .start and key .stop :
178+ queryset ._limit = key .stop - key .start
179+
182180 # Allow further QuerySet modifications to be performed
183181 return queryset
184- # Integer index provided
182+
183+ # Handle an index
185184 elif isinstance (key , int ):
186185 if queryset ._scalar :
187186 return queryset ._get_scalar (
188- queryset ._document ._from_son (queryset ._cursor [key ],
189- _auto_dereference = self ._auto_dereference ,
190- only_fields = self .only_fields ))
187+ queryset ._document ._from_son (
188+ queryset ._cursor [key ],
189+ _auto_dereference = self ._auto_dereference ,
190+ only_fields = self .only_fields
191+ )
192+ )
191193
192194 if queryset ._as_pymongo :
193195 return queryset ._get_as_pymongo (queryset ._cursor [key ])
194- return queryset ._document ._from_son (queryset ._cursor [key ],
195- _auto_dereference = self ._auto_dereference ,
196- only_fields = self .only_fields )
197196
198- raise AttributeError
197+ return queryset ._document ._from_son (
198+ queryset ._cursor [key ],
199+ _auto_dereference = self ._auto_dereference ,
200+ only_fields = self .only_fields
201+ )
202+
203+ raise AttributeError ('Provide a slice or an integer index' )
199204
200205 def __iter__ (self ):
201206 raise NotImplementedError
0 commit comments