From ec08d62a20f55cfdfb9fbd21d8bc5627c54337c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adam=20Kalin=CC=81ski?= Date: Sat, 22 Feb 2014 20:29:55 +0100 Subject: [PATCH] Fixed #22048 - Enhanced docs to cover nonexistent one-to-one relationships. Thanks EvilDMP for the suggestion. --- docs/ref/models/fields.txt | 9 +++++++++ docs/topics/db/examples/one_to_one.txt | 15 +++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index feaf846b24..3a43d51560 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -1469,6 +1469,15 @@ your resulting ``User`` model will have the following attributes:: >>> hasattr(user, 'supervisor_of') True +A ``DoesNotExist`` exception is raised when accessing the reverse relationship +if an entry in the related table doesn't exist. For example, if a user doesn't +have a supervisor designated by ``MySpecialUser``:: + + >>> user.supervisor_of + Traceback (most recent call last): + ... + DoesNotExist: User matching query does not exist. + .. _onetoone-arguments: Additionally, ``OneToOneField`` accepts all of the extra arguments diff --git a/docs/topics/db/examples/one_to_one.txt b/docs/topics/db/examples/one_to_one.txt index 89d422aecd..b66d52d369 100644 --- a/docs/topics/db/examples/one_to_one.txt +++ b/docs/topics/db/examples/one_to_one.txt @@ -61,10 +61,17 @@ A Place can access its restaurant, if available:: p2 doesn't have an associated restaurant:: - >>> p2.restaurant - Traceback (most recent call last): - ... - DoesNotExist: Restaurant matching query does not exist. + >>> from django.core.exceptions import ObjectDoesNotExist + >>> try: + >>> p2.restaurant + >>> except ObjectDoesNotExist: + >>> print("There is no restaurant here.") + There is no restaurant here. + +You can also use ``hasattr`` to avoid the need for exception catching:: + + >>> hasattr(p2, 'restaurant') + False Set the place using assignment notation. Because place is the primary key on Restaurant, the save will create a new restaurant::