(我有一个django 1.1.2和postgresql作为开发环境。) 我有两个问题:
tables = Table.objects.filter(is_active = True,
finishes_at__lt=datetime.datetime.now()
).order_by("-starts_at", "weight")[:20]
还有一个是
tables = Table.objects.filter(is_active = True,
finishes_at__lt=datetime.datetime.now()
).order_by("-starts_at", "weight")
除了第一个查询末尾有 [:20]
(LIMIT 20) 之外,这两个查询都是相同的。
但是当我运行这两个查询时。我看到结果集有不同的顺序。有办法纠正这个问题吗?
注意: 我在 dbshell 中运行查询,我看到查询实际上以不同的顺序给出结果。这是 django 生成的查询
SELECT "table_table"."id" FROM "table_table"
WHERE ("table_table"."is_active" = True
AND "table_table"."finishes_at" < '2010-11-09 11:57:48.482720' )
ORDER BY "table_table"."starts_at" DESC, "table_table"."weight" ASC
有限制的是
SELECT "table_table"."id" FROM "table_table"
WHERE ("table_table"."is_active" = True
AND "table_table"."finishes_at" < '2010-11-09 11:57:48.482720' )
ORDER BY "table_table"."starts_at" DESC, "table_table"."weight" ASC LIMIT 20
最佳答案
+1 了解详细信息,但对我来说,您实际上设法让 datetime.datetime.now()
产生相同的值并捕获 SQL 听起来有点可疑,所以请确认您确实传递了相同的值,并且上述 SQL 实际上已在日志中捕获。
就答案而言,我只能部分解决 - 从 SQL 的角度来看。 当针对相同的数据运行时,这两个 SQL 将产生相同的顺序。
您可以指望。
因此,如果 SQL 确实来自日志并且它们在相同的数据上运行,那么您要么在 django 端进一步操作,要么您的测试没有做好。
关于sql - 查询限制和顺序不能在 django 中一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4133154/