Code

Ticket #1463: m2o-patch.diff

File m2o-patch.diff, 1.9 KB (added by Malcolm Tredinnick <malcolm@…>, 8 years ago)

Return None when ForeignKey-related object does not exist

Line 
1Index: django/db/models/fields/related.py
2===================================================================
3--- django/db/models/fields/related.py  (revision 2485)
4+++ django/db/models/fields/related.py  (working copy)
5@@ -115,7 +115,7 @@
6         except AttributeError:
7             val = getattr(instance, self.field.attname)
8             if val is None:
9-                raise self.field.rel.to.DoesNotExist
10+                return val
11             other_field = self.field.rel.get_related_field()
12             if other_field.rel:
13                 params = {'%s__pk' % self.field.rel.field_name: val}
14Index: tests/modeltests/m2o_recursive/models.py
15===================================================================
16--- tests/modeltests/m2o_recursive/models.py    (revision 2485)
17+++ tests/modeltests/m2o_recursive/models.py    (working copy)
18@@ -31,9 +31,6 @@
19 >>> r.child_set.get(name__startswith='Child')
20 Child category
21 >>> r.parent
22-Traceback (most recent call last):
23-    ...
24-DoesNotExist
25 
26 >>> c.child_set.all()
27 []
28Index: tests/modeltests/many_to_one_null/models.py
29===================================================================
30--- tests/modeltests/many_to_one_null/models.py (revision 2485)
31+++ tests/modeltests/many_to_one_null/models.py (working copy)
32@@ -62,22 +62,16 @@
33 >>> a3.id
34 3
35 >>> a3.reporter
36-Traceback (most recent call last):
37-    ...
38-DoesNotExist
39 
40 >>> a3 = Article.objects.get(pk=3)
41 >>> print a3.reporter.id
42 Traceback (most recent call last):
43-    ...
44-DoesNotExist
45+   ...
46+AttributeError: 'NoneType' object has no attribute 'id'
47 
48-# Accessing an article's 'reporter' attribute throws ReporterDoesNotExist
49-# if the reporter is set to None.
50+# Accessing an article's 'reporter' attribute returns None if the reporter is
51+# set to None.
52 >>> a3.reporter
53-Traceback (most recent call last):
54-    ...
55-DoesNotExist
56 
57 # To retrieve the articles with no reporters set, use "reporter__isnull=True".
58 >>> Article.objects.filter(reporter__isnull=True)