Skip to content

Commit

Permalink
Added support to fetch latest object from mongoengine queryset
Browse files Browse the repository at this point in the history
Update tests

Handle comment to address the incosistent behaviour
  • Loading branch information
Arpit authored and ArpitSachan committed Aug 22, 2024
1 parent 090e6e1 commit c9fd9ff
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
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

0 comments on commit c9fd9ff

Please sign in to comment.