However, this leads to a query being run for each person in order to access the person's name, which I find to be really unnecessary. I only want to run one query per group -- will I have to use raw SQL to do this? My initial thought was to run a query that returns all the people in a group, and then cycling through the queryset to append the names into a list and then attaching the list to the project object.

Nested iteration through related models

On Tue, Dec 21, 2010 at 9:48 PM, Dopster <ken.kyhu...@gmail.com> wrote:> Let's say I have the following models:>> class Group(models.Model):> group_name = models.CharField(max_length=20)>> class Person(models.Model):> group = models.ForeignKey(Group)> name = models.CharField(max_length=50)>> How do I get an output of the following?>> GroupA: John, Stacy, Pete> GroupB: Bob, Bill, Mary>> I want to cycle through the groups and then output the people in each group.> In rough pseudo-code:>> groups = Group.objects.all()>> for g in groups:> print g.group_name, ": "> for p in g.person_set.all:> print p.person>> However, this leads to a query being run for each person in order to access> the person's name, which I find to be really unnecessary. I only want to run> one query per group -- will I have to use raw SQL to do this? My initial> thought was to run a query that returns all the people in a group, and then> cycling through the queryset to append the names into a list and then> attaching the list to the project object.>

Are you sure? What you have written should result in precisely whatyou asked for, 1 query to get the list of groups, 1 query per group toget the list of users. Your pseudo-code is a little wrong (for p ing.person_set.all(): print p.person - isn't p already a person? :), butif I correct that (and use standard contrib.auth models):

No, that's even worse - that is one query to get the list of people,and one query per person to build their group model object. If theifchanged checked 'p.group_id' instead of 'p.group', then that avoidunnecessarily instantiating the group object, and would cut it down tonum_groups + 1 queries.