When passing this QuerySet (all_postop_labs) to template.render(…), the ORM is re-querying each object by its PK which is causing very poor performance. I am following the exact same coding pattern for other objects and this behavior does not occur - the objects are pre-fetched in the original .raw call. No subsequent querying of the database occurs.
What may be the root cause for the ORM re-querying the database by PK for every instance in the QuerySet? I am at a loss for what I am doing wrong.
Well after 4-5 hours of struggle, I figured out the root cause thanks to a SQL Trace.
There was one field in the database that had one character having a different case than the case of the same character as defined in models.py. I noticed this because Django was only querying this field and the PK, based on each PK value.
So effectively, because the case of the fields did not match - the ORM auto-mapper did not match the fields, causing the ORM to re-query every row returned in the original QuerySet to finish loading all the data when the data was access (lazy load in this case).
I probably would not have figured this out w/out a SQL Trace.