Determining if one-to-many relation exists

1 view
Skip to first unread message

Malcolm Tredinnick

unread,
Mar 1, 2006, 10:06:51 PM3/1/06
to django-d...@googlegroups.com
I have been going through some code this morning and moving it over to
magic-removal. One of my models has a ForeignKey field that is
optionally empty. Before I can attempt to access the value of the
ForeignKey, I first need to check that it exists, so I have a few places
where the code says

if self.source_id:
source = self.source.name
else:
source = ''

where 'source' is defined as models.ForeignKey(null = True, blank =
True, ...).

The model-api.txt file still says that we should not need to ever access
the hidden source_id field except when hand-constructing SQL, so I was
wondering if there was some other way of establishing that the related
value existed in a case like the above? Or is the source_id "hack" still
the recommended solution (in which case I have a documentation patch to
make)? It felt a bit messy when I first wrote this code, I remember, so
maybe magic-removal is the time to tidy things up.

Note that just accessing self.source in the above code throws a
DoesNotExist exception from inside django/db/models/fields/related.py
(both in magic-removal and trunk).

Is it worth either fixing the attribute lookup to return None in the
above case, or adding a self.source.exists attribute (returns true or
false)? Then we can truly hide all references to source_id.

My preference would be to return None, since making 'object.exists'
return something when all other uses of 'object' raise a DoesNotExist
exception could be a bit counter-intuitive.

Regards,
Malcolm

Russell Keith-Magee

unread,
Mar 4, 2006, 8:03:35 PM3/4/06
to django-d...@googlegroups.com
On 3/2/06, Malcolm Tredinnick <mal...@pointy-stick.com> wrote:

> Is it worth either fixing the attribute lookup to return None in the
> above case, or adding a self.source.exists attribute (returns true or
> false)? Then we can truly hide all references to source_id.

Hi Malcolm,

I'm in the process of working out the last kinks in descriptor
behaviour - the exception throwing is one of those kinks. I'm hoping
to have this finalized in the next couple of days.

Yours,
Russ Magee

Reply all
Reply to author
Forward
0 new messages