Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 6th, 2012  |  syntax: None  |  size: 0.83 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Django annotation with nested filter
  2. for student in Student.objects.all():
  3.     student.num_excused_absence = Attendance.objects.filter(student=student, type="Excused").count()
  4.        
  5. # a query for students
  6. students = Students.objects.all()
  7. # a query to count the student attendances, grouped by type.
  8. attendance_counts = Attendence(student__in=students).values('student', 'type').annotate(abs=Count('pk'))
  9. # regroup that into a dictionary {student -> { type -> count }}
  10. from itertools import groupby
  11. attendance_s_t = dict((s, (dict(t, c) for (s, t, c) in g)) for s, g in groupby(attendance_counts, lambda (s, t, c): s))
  12. # then use them efficiently:
  13. for student in students:
  14.     student.absences = attendance_s_t.get(student.pk, {}).get('Excused', 0)
  15.        
  16. excused = Student.objects.filter(attendance__type='Excused').annotate(abs=Count('attendance'))