Skip to content

Commit

Permalink
Implemented .get() with __default kwarg
Browse files Browse the repository at this point in the history
  • Loading branch information
akaariai committed Oct 9, 2012
1 parent 8c42744 commit 3ea7115
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 1 deletion.
2 changes: 2 additions & 0 deletions django/db/models/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@
# Separator used to split filter strings apart.
LOOKUP_SEP = '__'

# A marker for .get()
RAISE_ERROR = object()
5 changes: 4 additions & 1 deletion django/db/models/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from django.core import exceptions
from django.db import connections, router, transaction, IntegrityError
from django.db.models.constants import LOOKUP_SEP
from django.db.models.constants import LOOKUP_SEP, RAISE_ERROR
from django.db.models.fields import AutoField
from django.db.models.query_utils import (Q, select_related_descend,
deferred_class_factory, InvalidQuery)
Expand Down Expand Up @@ -365,13 +365,16 @@ def get(self, *args, **kwargs):
Performs the query and returns a single object matching the given
keyword arguments.
"""
default_if_none = kwargs.pop('__default', RAISE_ERROR)
clone = self.filter(*args, **kwargs)
if self.query.can_filter():
clone = clone.order_by()
num = len(clone)
if num == 1:
return clone._result_cache[0]
if not num:
if default_if_none != RAISE_ERROR:
return default_if_none
raise self.model.DoesNotExist(
"%s matching query does not exist. "
"Lookup parameters were %s" %
Expand Down
3 changes: 3 additions & 0 deletions tests/modeltests/basic/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ def test_lookup(self):
Article.objects.get,
id__exact=2000,
)
# This can be overridden with .__default
self.assertEqual(Article.objects.get(id__exact=2000, __default=None),
None)
# To avoid dict-ordering related errors check only one lookup
# in single assert.
six.assertRaisesRegex(self,
Expand Down

0 comments on commit 3ea7115

Please sign in to comment.