jAC
jAC

Reputation: 3445

django how to group on ManyToMany relationship dynamically

I have what I believe is a simple request but I have been beating my head against a wall and I am not getting any smarter for it.

I am using django 1.10. What I am trying to do is get a list of my members grouped by my family field

The models look like this:

class Family(models.Model):
    family_name = models.CharField(max_length=200)

class Member(models.Model):
    name = models.OneToOneField(User)
    family = models.ManyToManyField(Family,blank=True,related_name='members')

So i can set my view to use

members = Member.objects.order_by('family')

or

members = Family.objects.order_by('family_name')

This obviously holds my members or my families but not both. How would i get this to have both the member name and their family and then group by it?

An Example of the output i am looking for is:

Family 1

Family 2

Any help would be appreciated.

Upvotes: 1

Views: 2114

Answers (1)

user2390182
user2390182

Reputation: 73498

What's wrong with the first one? If you want to order it by the family's name, do:

members = Member.objects.order_by('family__family_name')

These members all have their family available via .family. If you want to save db queries when you are looping through these members and access their families, you can add a select_related:

members = Member.objects.order_by('family__family_name').select_related('family')

On the other hand, if you really want families and then loop through their members, do:

families = Family.objects.order_by('family_name').prefetch_related('members')
for fam in families:
    // do sth. with family
    for mem in fam.members.all():
        // do sth. with member

The prefetch_related will make this run with only 2 db queries, no matter how many families or members.

Upvotes: 1

Related Questions