Using the reverse relation of `OneToOneField`

23 views
Skip to first unread message

Ram Rachum

unread,
Jul 11, 2012, 8:27:01 AM7/11/12
to pyweb-il
Hey guys,

I just stumbled into something weird.

I have a OneToOneField from Chair to Table. Let's say that it's called `.table`, and the reverse is called `.chair`.

Now, I've got a Table, and I want to see whether it has a chair associated with it. How could I check this? I assumed that I will just check whether `table.chair` is None or not, but apparently it's not how it works. If there is no chair associated with the table, you don't get `None`, you get a `DoesNotExist` exception!

Now, I could whip up a try...except block, but that strikes me as an ugly solution. I'd sooner make a helper property that will do this for me.

Is there a nicer way to check whether a Table has a Chair?


Thanks,
Ram.

Shai Berger

unread,
Jul 11, 2012, 8:38:20 AM7/11/12
to pywe...@googlegroups.com
As with all single-valued relations in Django, there's an "_id" property.

if tab.chair_id:
...

Ram Rachum

unread,
Jul 11, 2012, 8:41:24 AM7/11/12
to pywe...@googlegroups.com
Thanks, I didn't think about that and it's good to know about it

Still, I find it too low-level for my taste, so I think I'll stick with the helper property. I hope that Django will introduce a nicer way of doing this.


Thanks!


--
You received this message because you are subscribed to the Google Groups "PyWeb-IL" group.
To post to this group, send email to pywe...@googlegroups.com.
To unsubscribe from this group, send email to pyweb-il+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/pyweb-il?hl=en.


Udi Oron

unread,
Jul 11, 2012, 9:51:27 AM7/11/12
to pywe...@googlegroups.com
Hi!


On Wed, Jul 11, 2012 at 3:38 PM, Shai Berger <sh...@platonix.com> wrote:
if tab.chair_id:
        ...

There is no x_id attribute for reverse one-to-one relationships in Django.

On the db level, only the 'table' table holds an actual field.
Getting the t.chair property triggers a Chair.objects.get(table_id=t.id) query.

You can easily craft a chair_or_none property or method, with a try block.
However, you should cache the response:  AFAIK DoesNotExist exceptions are not cached.
i.e. start with:
c = t.chair_or_none()
# now do stuff with c

(But how can you invite people for dinner with only one chair next to your table?)

Udi.

Ram Rachum

unread,
Jul 11, 2012, 9:55:52 AM7/11/12
to pywe...@googlegroups.com
Thanks Udi!

--
Reply all
Reply to author
Forward
0 new messages