It indeed does not care about the order, since the query looks like:
SELECT model.*
FROM model
WHERE model.pk IN (3, 2, 1, 42)
The database can return the values in any order it wants. Depending on the database you use, the indexing mechanism, etc. the order can be "deterministic", but it is even possible that it will return records completely random.
You can order these, with a rather complicates expression:
from django.db.models import Case, IntegerField, Value, When
my_ids = [3,2,1,42]
Model.objects.filter(
pk__in=my_ids
).order_by(
Case(
*[When(pk=pk, then=Value(i)) for i, pk in enumerate(my_ids)],
output_field=IntegerField()
).asc()
)
This is still a QuerySet
, and can be used for lazy querying purposes, but the question remains why you want to sort the elements based on the order of the primary keys. Usually the model (or a related model) contains more "interesting" ways to order elements.