mirror of
https://github.com/django/django.git
synced 2025-09-25 03:32:37 +00:00
Fixed #19326 -- Added first() and last() methods to QuerySet
This commit is contained in:
parent
d595b61aca
commit
ea9a0857d4
5 changed files with 92 additions and 0 deletions
|
@ -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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue