mirror of
https://github.com/django/django.git
synced 2025-10-29 16:46:11 +00:00
Fixed #19326 -- Added first() and last() methods to QuerySet
This commit is contained in:
committed by
Anssi Kääriäinen
parent
d595b61aca
commit
ea9a0857d4
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user