Last active
May 12, 2022 11:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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