Fixed #19326 -- Added first() and last() methods to QuerySet

This commit is contained in:
Selwin Ong 2013-05-21 18:35:12 +03:00 committed by Anssi Kääriäinen
parent d595b61aca
commit ea9a0857d4
5 changed files with 92 additions and 0 deletions

View file

@ -498,6 +498,26 @@ class QuerySet(object):
def latest(self, field_name=None):
return self._earliest_or_latest(field_name=field_name, direction="-")
def first(self):
"""
Returns the first object of a query, returns None if no match is found.
"""
qs = self if self.ordered else self.order_by('pk')
try:
return qs[0]
except IndexError:
return None
def last(self):
"""
Returns the last object of a query, returns None if no match is found.
"""
qs = self.reverse() if self.ordered else self.order_by('-pk')
try:
return qs[0]
except IndexError:
return None
def in_bulk(self, id_list):
"""
Returns a dictionary mapping each of the given IDs to the object with