views:

192

answers:

1

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?

+3  A: 

Your slice syntax is wrong. The value after the colon is not the count of elements to get, but the index of the end of the slice. Using 'median' on its own without a colon, as you do in your second example, would work.

Daniel Roseman
Thanks, I was getting the slice syntax mixed up with the MySQL limit syntax
handsofaten