jAC jAC - 1 year ago 73
Python Question

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')


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

  • Member 1

  • Member 2

Family 2

  • Member 1

  • Member 3

Any help would be appreciated.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download