29๐
.order_by
performs sorting at database level.
Here is an example. We store lasy queryset in var results
. No query has been made yet:
results = SampleModel.objects.filter(field_A="foo")
Touch the results
, for example, by iterating it:
for r in results: # here query was send to database
# ...
Now, if weโll do it again, no attempt to database will be made, as we already have this exact query:
for r in results: # no query send to database
# ...
But, when you apply .order_by
, the query will be different. So, django has to send new request to database:
for r in results.order_by('?'): # new query was send to database
# ...
Solution
When you do the query in django, and you know, that you will get all elements from that query (i.e., no OFFSET and LIMIT), then you can process those elements in python, after you get them from database.
results = list(SampleModel.objects.filter(field_A="foo")) # convert here queryset to list
At that line query was made and you have all elements in results
.
If you need to get random order, do it in python now:
from random import shuffle
shuffle(results)
After that, results will have random order without additional query being send to database.