Django QuerySet filter + order_by + limit

12,629

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.

Share:
12,629
bjudson
Author by

bjudson

Updated on June 04, 2022

Comments

  • bjudson
    bjudson almost 2 years

    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?