Opened 19 years ago

Closed 19 years ago

#1463 closed defect (fixed)

[patch] [magic-removal] Return None when accessing a non-existent relation entry

Reported by: Malcolm Tredinnick <malcolm@…> Owned by: Adrian Holovaty
Component: Core (Other) Version: magic-removal
Severity: normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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:

old

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 = ''

new

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...)

Attachments (1)

m2o-patch.diff (1.9 KB ) - added by Malcolm Tredinnick <malcolm@…> 19 years ago.
Return None when ForeignKey-related object does not exist

Download all attachments as: .zip

Change History (4)

by Malcolm Tredinnick <malcolm@…>, 19 years ago

Attachment: m2o-patch.diff added

Return None when ForeignKey-related object does not exist

comment:1 by Antti Kaihola, 19 years ago

Makes sense. I hope this gets through.

comment:2 by Max Battcher <me@…>, 19 years ago

Agreed. This also would simplify the Template resolve_variable code, too. (Which my own #1396 fixes the hard way.)

comment:3 by Malcolm Tredinnick <malcolm@…>, 19 years ago

Resolution: fixed
Status: newclosed

This was fixed as part of Russell's descriptor changes (in [2511]).

Note: See TracTickets for help on using tickets.
Back to Top