Code

Ticket #5741: get_default.diff

File get_default.diff, 1.9 KB (added by dcwatson, 7 years ago)
Line 
1Index: django/db/models/query.py
2===================================================================
3--- django/db/models/query.py   (revision 6473)
4+++ django/db/models/query.py   (working copy)
5@@ -254,12 +254,18 @@
6
7     def get(self, *args, **kwargs):
8         "Performs the SELECT and returns a single object matching the given keyword arguments."
9+        has_default = False
10+        if 'default' in kwargs:
11+            default_value = kwargs.pop('default')
12+            has_default = True
13         clone = self.filter(*args, **kwargs)
14         # clean up SQL by removing unneeded ORDER BY
15         if not clone._order_by:
16             clone._order_by = ()
17         obj_list = list(clone)
18         if len(obj_list) < 1:
19+            if has_default:
20+                return default_value
21             raise self.model.DoesNotExist, "%s matching query does not exist." % self.model._meta.object_name
22         assert len(obj_list) == 1, "get() returned more than one %s -- it returned %s! Lookup parameters were %s" % (self.model._meta.object_name, len(obj_list), kwargs)
23         return obj_list[0]
24Index: docs/db-api.txt
25===================================================================
26--- docs/db-api.txt     (revision 6473)
27+++ docs/db-api.txt     (working copy)
28@@ -839,6 +839,16 @@
29     except ObjectDoesNotExist:
30         print "Either the entry or blog doesn't exist."
31
32+**New in Django development version**
33+
34+``get()`` may take a kwarg named ``default``, similar to the ``get()`` method
35+on dicts. When ``default`` is specified, and no object is found, the value of
36+``default`` is returned. If ``default`` is not specified, the ``DoesNotExist``
37+exception is raised as usual.
38+
39+For existing models with a field named ``default``, the more verbose
40+``default__exact`` lookup syntax must be used.
41+
42 ``create(**kwargs)``
43 ~~~~~~~~~~~~~~~~~~~~
44