Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

magic-removal: Modified descriptor to return None rather than raising…

… DoesNotExist if null=True for a related field.

git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@2511 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 7a0b04fdc3abb8ff4db7ffc81d4a0201f682a82a 1 parent a5bd054
@freakboy3742 freakboy3742 authored
View
3  django/db/models/fields/related.py
@@ -117,6 +117,9 @@ def __get__(self, instance, instance_type=None):
except AttributeError:
val = getattr(instance, self.field.attname)
if val is None:
+ # If Null is an allowed value, return it.
+ if self.field.null:
+ return None
raise self.field.rel.to.DoesNotExist
other_field = self.field.rel.get_related_field()
if other_field.rel:
View
6 tests/modeltests/m2o_recursive/models.py
@@ -30,10 +30,8 @@ def __repr__(self):
[Child category]
>>> r.child_set.get(name__startswith='Child')
Child category
->>> r.parent
-Traceback (most recent call last):
- ...
-DoesNotExist
+>>> print r.parent
+None
>>> c.child_set.all()
[]
View
17 tests/modeltests/many_to_one_null/models.py
@@ -61,23 +61,20 @@ class Meta:
>>> a3.save()
>>> a3.id
3
->>> a3.reporter
-Traceback (most recent call last):
- ...
-DoesNotExist
+>>> print a3.reporter
+None
+# Need to reget a3 to refresh the cache
>>> a3 = Article.objects.get(pk=3)
>>> print a3.reporter.id
Traceback (most recent call last):
...
-DoesNotExist
+AttributeError: 'NoneType' object has no attribute 'id'
-# Accessing an article's 'reporter' attribute throws ReporterDoesNotExist
+# Accessing an article's 'reporter' attribute returns None
# if the reporter is set to None.
->>> a3.reporter
-Traceback (most recent call last):
- ...
-DoesNotExist
+>>> print a3.reporter
+None
# To retrieve the articles with no reporters set, use "reporter__isnull=True".
>>> Article.objects.filter(reporter__isnull=True)
Please sign in to comment.
Something went wrong with that request. Please try again.