Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support to fetch latest object from mongoengine queryset #2757

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions mongoengine/queryset/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,23 @@ def first(self):
result = None
return result

def last(self):
"""Retrieve the latest object matching the query."""
if not self._ordering:
raise OperationError(
"Cannot use `last()` without ordering. Use `order_by()` on the queryset first."
)

queryset = self.clone()
if self._none or self._empty:
return None

try:
result = queryset[self.count() - 1]
except IndexError:
result = None
return result

def insert(
self, doc_or_docs, load_bulk=True, write_concern=None, signal_kwargs=None
):
Expand Down
26 changes: 26 additions & 0 deletions tests/queryset/test_queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2599,6 +2599,32 @@ def test_order_by(self):
ages = [p.age for p in self.Person.objects.order_by("")]
assert ages == [40, 20, 30]

def test_last(self):
"""Ensure the retrieval of the latest object from the QuerySet based on the specified ordering."""
person1 = self.Person(name="User B", age=40).save()
person2 = self.Person(name="User A", age=20).save()
person3 = self.Person(name="User C", age=30).save()

assert self.Person.objects.order_by("age").last() == person1
assert self.Person.objects.order_by("-age").last() == person2

person2.age = 31
person2.save()
assert self.Person.objects.order_by("-age").last() == person3
assert self.Person.objects.order_by("age").last() == person1

person1.age = 41
person1.save()
assert self.Person.objects.order_by("age").last() == person1

assert self.Person.objects.order_by("name").last() == person3

assert self.Person.objects.filter(age__lt=40).order_by("age").last() == person2
assert self.Person.objects.filter(age__gt=50).order_by("age").last() is None

with pytest.raises(OperationError):
self.Person.objects.last()

def test_order_by_optional(self):
class BlogPost(Document):
title = StringField()
Expand Down
Loading