Django QuerySet filter + order_by + limit
- by handsofaten
So I have a Django app that processes test results, and I'm trying to find the median score for a certain assessment. I would think that this would work:
e = Exam.objects.all()
total = e.count()
median = int(round(total / 2))
median_exam = Exam.objects.filter(assessment=assessment.id).order_by('score')[median:1]
median_score = median_exam.score
But it always returns an empty list. I can get the result I want with this:
e = Exam.objects.all()
total = e.count()
median = int(round(total / 2))
exams = Exam.objects.filter(assessment=assessment.id).order_by('score')
median_score = median_exam[median].score
I would just prefer not to have to query the entire set of exams. I thought about just writing a raw MySQL query that looks something like:
SELECT score FROM assess_exam WHERE assessment_id = 5 ORDER BY score LIMIT 690,1
But if possible, I'd like to stay within Django's ORM. Mostly, it's just bothering me that I can't seem to use order_by with a filter and a limit. Any ideas?