开发者

Django QuerySet filter + order_by + limit

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 t开发者_运维百科o 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜