Code

Opened 8 years ago

Closed 8 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:

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@…> 8 years ago.
Return None when ForeignKey-related object does not exist

Download all attachments as: .zip

Change History (4)

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

Return None when ForeignKey-related object does not exist

comment:1 Changed 8 years ago by akaihola

Makes sense. I hope this gets through.

comment:2 Changed 8 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 8 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]).

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.