Django 查询集过滤器 + order_by +限制
因此,我有一个处理测试结果的 Django 应用程序,并且我正在尝试查找某个评估的中位数分数。我认为这会起作用:
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
但它总是返回一个空列表。我可以这样得到我想要的结果:
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
我只是不想查询整套考试。我想过只编写一个原始的 MySQL 查询,如下所示:
SELECT score FROM assess_exam WHERE assessment_id = 5 ORDER BY score LIMIT 690,1
但如果可能的话,我想留在 Django 的 ORM 中。大多数情况下,我似乎无法将 order_by 与过滤器和限制一起使用,这让我很困扰。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的切片语法错误。冒号后面的值不是要获取的元素数,而是切片末尾的索引。正如您在第二个示例中所做的那样,单独使用“中位数”而不使用冒号是可行的。
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.