We moved away from the ORM in Django because of this problem. Basically, if you try and do
for p in person:
print p.car.colour
The ORM will happily return all people (typically as instances of a Person object), but then it will need to query the car table for each Person.
A simple and very effective approach to this is something I call "**fanfolding**", which avoids the nonsensical idea that query results from a relational database should map back to the original tables from which the query is composed.
Step 1: Wide select
select * from people_car_colour; # this is a view or sql function
This will return something like
p.id | p.name | p.telno | car.id | car.type | car.colour
-----+--------+---------+--------+----------+-----------
2 | jones | 2145 | 77 | ford | red
2 | jones | 2145 | 1012 | toyota | blue
16 | ashby | 124 | 99 | bmw | yellow
Step 2: Objectify
Suck the results into a generic object creator with an argument to split after the third item. This means that "jones" object won't be made more than once.
Step 3: Render
for p in people:
print p.car.colour # no more car queries
See [this web page][1] for an implementation of **fanfolding** for python.
[1]:
[To see links please register here]