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()