Left Join with a OneToOne field in Django

Posted by jamida on Stack Overflow See other posts from Stack Overflow or by jamida
Published on 2010-05-21T17:41:43Z Indexed on 2010/05/21 20:11 UTC
Read the original article Hit count: 493

Filed under:
|

I have 2 tables, simpleDB_all and simpleDB_some. The "all" table has an entry for every item I want, while the "some" table has entries only for some items that need additional information. The Django models for these are:

class all(models.Model):
    name = models.CharField(max_length=40)
    important_info = models.CharField(max_length=40)

class some(models.Model):
    all_key = models.OneToOneField(all)
    extra_info = models.CharField(max_length=40)

I'd like to create a view that shows every item in "all" with the extra info if it exists in "some". Since I'm using a 1-1 field I can do this with almost complete success:

allitems = all.objects.all()
for item in allitems:
    print item.name, item.important_info, item.some.extra_info

but when I get to the item that doesn't have a corresponding entry in the "some" table I get a DoesNotExist exception.

Ideally I'd be doing this loop inside a template, so it's impossible to wrap it around a "try" clause. Any thoughts?

I can get the desired effect directly in SQL using a query like this:

SELECT all.name, all.important_info, some.extra_info
    FROM all LEFT JOIN some ON all.id = some.all_key_id;

But I'd rather not use raw SQL.

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models