Skip to content

Commit 31df545

Browse files
committed
Handle comment to address the incosistent behaviour
1 parent 92a81dc commit 31df545

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

mongoengine/queryset/base.py

+12-9
Original file line numberDiff line numberDiff line change
@@ -298,17 +298,20 @@ def first(self):
298298
result = None
299299
return result
300300

301-
def last(self, *ordering_keys):
302-
"""Retrieve the latest object matching the query.
301+
def last(self):
302+
"""Retrieve the latest object matching the query."""
303+
if not self._ordering:
304+
raise OperationError("Cannot use `last()` without ordering. Use `order_by()` on the queryset first.")
303305

304-
:param keys: fields to order the query results by; keys may be
305-
prefixed with "+" or a "-" to determine the ordering direction.
306-
307-
"""
308-
if not ordering_keys:
309-
ordering_keys = "-id"
306+
queryset = self.clone()
307+
if self._none or self._empty:
308+
return None
310309

311-
return self.order_by(ordering_keys).first()
310+
try:
311+
result = queryset[-1]
312+
except IndexError:
313+
result = None
314+
return result
312315

313316
def insert(
314317
self, doc_or_docs, load_bulk=True, write_concern=None, signal_kwargs=None

0 commit comments

Comments
 (0)