Left Join with a OneToOne field in Django
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, i开发者_如何学Gotem.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.
You won't get a DoesNotExist
exception in the template - they are hidden, by design, by the template system.
The SQL you give is what is generated, more or less, when you use select_related
on your query (if you're using Django 1.2 or a checkout more recent than r12307, from February):
allitems = all.objects.select_related('some')
精彩评论