2๐
โ
I have 3 models: Pupils, Instructor, Group. They are connected through
the Pupils model like so:
This means that you have a M2M relation between Instructor
and Group
which you can define like this:
class Instructor:
#...
groups = models.ManyToManyField(Group, through='Pupils')
Now using this M2M relation, you can take an instructor
groups like this:
instructor.groups.all()
you can also use the reverse relation
of the M2M relation in order to get all instructors for a group.
group.instructor_set.all()
you can also get the instructors count by using .count()
#group instructors count
group.instructor_set.count()
#or if you want to count pupils,
#use the reverse relation of the ForeignKey
#group.pupils_set.count()
Now about the 2nd part of the question if I understand it correctly you need something like this:
#this will give you instructors of a group with their pupils count.
group.instructor_set.annotate(pupils_count=Count('pupils'))
๐คTodor
Source:stackexchange.com