[patch] [magic-removal] Return None when accessing a non-existent relation entry
|Reported by:||Owned by:||Adrian Holovaty|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I initially mentioned this problem in http://groups.google.com/group/django-developers/browse_frm/thread/4fb78d1de053249a/ . It is currently impossible to tell if the other end of a ForeignKey field exists without either constructing a try...except block or using the not-recommended (according to the docs) fieldname_id attribute.
The attached patch changes the behaviour to return None if there is no related entry, rather than raising an exception. It also updates the tests to match this change. User code now changes as follows:
if self.parent_id: # Not recommended for use in docs/model-api.txt. Magic attribute. my_parent = self.parent.name else: my_parent = '' try: my_parent = self.parent.name except DoesNotExist: my_parent = ''
if self.parent: my_parent = self.parent.name else: my_parent = ''
I realise this change may be viewed as "too much effort for no real gain", so I won't be completely heart-broken if a credible developer closes it as wontfix. But using try...except blocks for standard code paths (which is the case here, when you can have empty relations, such as in a hierarchy) or forcing the use of a magically created attribute (parent_id in the above case), both feel more awkward to me. The relation does not exist, so using None as the related object feels more natural. (ok... getting off the soapbox now...)