Opened 10 years ago

Closed 10 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
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: UI/UX:


I initially mentioned this problem in . 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 =
    my_parent = ''

    my_parent =
except DoesNotExist:
    my_parent = ''


if self.parent:
   my_parent =
   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@…> 10 years ago.
Return None when ForeignKey-related object does not exist

Download all attachments as: .zip

Change History (4)

Changed 10 years ago by Malcolm Tredinnick <malcolm@…>

Return None when ForeignKey-related object does not exist

comment:1 Changed 10 years ago by akaihola

Makes sense. I hope this gets through.

comment:2 Changed 10 years ago by Max Battcher <me@…>

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

comment:3 Changed 10 years ago by Malcolm Tredinnick <malcolm@…>

  • Resolution set to fixed
  • Status changed from new to closed

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

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