(I have a django 1.1.2 and postgresql as development environment.)
I have two queries:
tables = Table.objects.filter(is_active = True,
finishes_at__lt=datetime.datetime.now()
).order_by("-starts_at", "weight")[:20]
and the other one is
tables = Table.objects.filter(is_active = True,
finishes_at__lt=datetime.datetime.now()
).order_by("-starts_at", "weight")
Both of those queries are same except the first one has [:20] (LIMIT 20) at the end.
But When I run both of those queries. I saw that resultsets have different orders. Is there a way to correct this?
Note:
I run the queries in dbshell and I saw that queries actually giving results in different order. here are the queries django generated
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
and the one with the limit is
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 for the details, however it sounds a bit fishy to me that you actually managed to get
datetime.datetime.now()to produce the same value and capture the SQL, so please confirm that you actually did pass the same value and that the above SQL’s were actually captured in the log.As far as the answer goes, I can only address it partially – from the point of SQLs.
The two SQLs will produce the same order when run against the same data.
You can count on that.
So providing that SQL’s do come from the log and that they were run on the same data you are either further manipulating thing on the django side or your testing was not done well.