Django 查询集过滤器 + order_by +限制

发布于 2024-09-05 09:08:26 字数 768 浏览 6 评论 0原文

因此,我有一个处理测试结果的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赤濁 2024-09-12 09:08:26

您的切片语法错误。冒号后面的值不是要获取的元素数,而是切片末尾的索引。正如您在第二个示例中所做的那样,单独使用“中位数”而不使用冒号是可行的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文