For example lets say I have a model named “ClassRoom” and a model named “Student” and Student has a foreign key relationship with ClassRoom.
Class Student(models.Model):
classroom = models.ForeignKey(ClassRoom, related_name='student')
How can I Find which class room has the most students in it with a basic Django query. What I did to find the answer seems like it should be easier.
max = 0
for c in ClassRoom.objects.all():
if c.student.count() > max:
print 'ID: %s' % c.id
max = c.student.count()
and I would then take the last ID printed and do a .get() query on the class room ID. Is there anyway to do this with annotation or aggregate perhaps?
Try adding something like this to your
ClassRoomobject:Obviously replace
classroomwith whatever you called it. Then you should be able to use the__maxquery.Disclaimer: I haven’t tried this, but it works in my head 🙂