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:
family_name = models.CharField(max_length=200)
name = models.OneToOneField(User)
family = models.ManyToManyField(Family,blank=True,related_name='members')
members = Member.objects.order_by('family')
members = Family.objects.order_by('family_name')
What's wrong with the first one? If you want to order it by the family's
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
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.