I assume that JOINs (so select_related ) are not important for query speed. In any case, when you execute the values() query, you really don't need select_related , because only the fields you will ever get are those that are specified as values() arguments, and they are still retrieved by JOIN.
To understand why this takes so long, you can do the following:
Print "raw sql" with
print tbl_action_log.objects.order_by('-TicketID', '-ActionLogID').query
Modify it (it is not actually SQL, but it should be enough), which will be run in the SQL client, for example django own manage.py dbshell .
Run it, pay attention to the time. Then execute EXPLAIN ... (put your query in points), you will probably see the message "full table scan"
Add the appropriate index to the database table, by the affected columns, and run the query again. The index will probably be as follows:
CREATE INDEX idx_action_log_on_tkid_logid ON tbl_action_log (TicketID, ActionLogID);
When you are satisfied with the index, save its creation collection to the app/sql/modelname.sql , this will create the index in any new deployment.
source share