Hi, Python/Django newb here. I have a question regarding the best approach to rendering 1-to-many relationships in a template.
I have 2 tables, Customers and Cars, where a Customer can have many Cars, hence the 1-to-many relationship. I need to display all the Customers with all their Cars, like this: Customer1 Car: car1 Car: car2 Customer2 Car: car1 Car: car2 Car: car3 ... I've taken 2 approaches to solving this problem, described below. The first approach involves creating a complete Customers queryset, and then using a FOR loop inside the template to create a Cars queryset, once for each customer. The problem is obvious: if I have 10,000 customers, the Cars table is going to be queried 10,000 times (correct?). The DBA is going to be mad, and I'm going to look foolish. Here's the code: {% for customer in customers %} <li>{{ customer.full_name }}</li> <ul> {% for car in customer.car_set.all %} <li>Car: {{ car }}</li> {% endfor %} </ul> {% endfor %} My second approach involves both complete Customers and Cars querysets. Then, inside the template, iterate through the Cars queryset based on the current Customer.id, and then output the car. Here's the code: {% for customer in customers %} <li>{{ customer.full_name }}</li> <ul> {% for car in cars %} {% ifequal car.customer_id customer.id %} <li>Car: {{ car }}</li> {% endifequal %} {% endfor %} </ul> {% endfor %} I *think* the problem with the 2nd approach is that I'm forcing Python to iterate through the Cars queryset 10,000 times to find the car(s) belonging to each driver. Is there a 3rd, better/best approach to this problem? Thanks! --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---