How can I generate and display Django query sets from the results of another query set?

For example, 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) 

I want to list all the groups, and for each group a list of people in the group.

Group A: Person1, Person2, Person3
Group B: Person4, Person5, Person6

I am stuck in Group.objects.all (), which will only return a query containing Group objects that I can scroll in the template. However, I do not know how to get through the people in each group. Help?

 groups = Group.objects.all() {% for g in groups %} g.group_name: << Need an inner loop here to cycle through the people in each group? >> {% endfor %} 
+4
source share
3 answers

You can use the built-in regroup tag:

Template:

 {% regroup people by group as people_by_group %} {% for group in people_by_group %} {{ group.grouper.group_name }} {% for person in group.list %} {{ person }} {% endfor %} {% endfor %} 

Context:

 {'people': Person.objects.all().select_related('group').order_by('group')} 

This will not be a list of empty groups, but you can create a similar strucutre in your own view, for example:

 groups = list(Group.objects.all()) groups_map = dict((g.pk, g) for g in groups) for g in groups: g.person_cache = [] for person in Person.objects.all(): if person.group_id is not None: groups_map[person.group_id].person_cache.append(person) del groups_map # ``groups`` now contains a list suitable for your template 

This way you only make two requests. Using a linked manager in a loop will produce requests number_of_groups+1 .

+1
source

You need to request people instead of a group.

 people = Person.objects.select_related().order_by('group') {% for person in people %} {% ifchanged person.group %} {{ person.group }} {% endifchanged %} {{ person }} {% endfor %} 

This makes a single request for all people and related groups, sorted by groups. The ifchanged pattern in the pattern recognizes when you have moved to a new group and printed it.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1332935/


All Articles