Skip to content

Instantly share code, notes, and snippets.

@wolever
Last active May 12, 2022 11:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolever/eccb7ba72c38a902efc5 to your computer and use it in GitHub Desktop.
Save wolever/eccb7ba72c38a902efc5 to your computer and use it in GitHub Desktop.
Monkeypatch Django 1.5's QuerySet adding a .first() method compatible with 1.6
def monkeypatch_queryset_first():
""" Monkeypatch QuerySet adding a `.first()` method which is compatible
with Django 1.6's `.first()`. """
from django.db.models.query import QuerySet
if hasattr(QuerySet, "first"):
import warnings
warnings.warn("QuerySet.first is already defined! "
"Monkey patch should be removed.")
return
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
QuerySet.first = first
monkeypatch_queryset_first()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment