简体   繁体   中英

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

  • Member 1
  • Member 2

Family 2

  • Member 1
  • Member 3

Any help would be appreciated.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM