views:

40

answers:

1

Hey guys,

I am trying to do something very basic here with three models:

class Car(models.Model):
   country = models.ForeignKey(Country)
   company_name = models.CharField(max_length=50)
   continent = models.CharField(max_length=50)

class CountryProfile(models.Model):
   country = models.ForeignKey(Country)
   minimum_wage = models.IntField()

class Country(models.Model):
   name = models.CharField(max_length=50)

Basically, Car points to Country, and CountryProfile also points to Country. I was wondering how I could get all car's company names with continent equal to something and minimum wage associated with the country of a respective car company, without having to do two db calls.

Thanks!

A: 

Picking up the Country's details while querying for a Car is easy. Car has a foreign key pointing to Country and select_related() will do the trick.

Car.objects.select_related().filter()

However (as far as I know; please correct me if I am wrong) Django doesn't allow you to select "reverse relationships" using the select_related() call. This means you cannot pick up CountryProfile using a select_related call from Country. Which in turn means that you'd end up firing two queries.

If you are using Django 1.2 and are willing to fall back to raw SQL queries then you can get Car instances with additional information using a single (join) query.

Manoj Govindan
So, I guess there's no more efficient way to do this. Thanks for the response!
Peter
There are a couple of options if you don't mind stepping away from the Django ORM. 1) as I said above, use a combination of Django ORM and a custom SQL query. 2) This one is way more radical. Use SQLAlchemy to handle your joins in this case. See http://stackoverflow.com/questions/1154331/sqlalchemy-and-django-is-it-production-ready/1155407#1155407 for an example.
Manoj Govindan
Thx a lot, man!
Peter