1👍
Querysets are evaluated only when you slice them. In other terms the database is hit each time you perform a slicing operation (cf. Django documentation regarding this point).
Then, the question is: why isn’t the effect of your order_by
method the same for every evaluation? There might be several (non exclusive) explanations, depending on the content of your User
database table and on your variable sort_array
.
- The database has been updated between 2 evaluations of the queryset,
*sort_array
corresponds to a tuple which is not long, precise enough for the order to be fixed and unique. From the documentation:
A particular ordering is guaranteed only when ordering by a set of fields that uniquely identify each object in the results. For example, if a
name
field isn’t unique, ordering by it won’t guarantee objects with the same name always appear in the same order.
A simple solution would be to force the evaluation of your queryset before to perform slicing, by calling list()
on it:
my_list = list(User.pas1_objects.select_related("userlogindetails", "usermeta", "tenant")
.filter(data_filter)
.exclude(userrolepermissions__role_id__in=["PG", "PD"], tenant_id__in=tenant_ids)
.order_by(*sort_array)
)
# And then you can slice your list without any risk of inconsistency
my_list[0:1]