# ORM re-querying rows by pk when iterating QuerySet after .raw load

**URL:** <https://forum.djangoproject.com/t/orm-re-querying-rows-by-pk-when-iterating-queryset-after-raw-load/39334>\
**Category:** Using the ORM\
**Created:** [March 6, 2025, 1:45pm UTC](https://forum.djangoproject.com/t/orm-re-querying-rows-by-pk-when-iterating-queryset-after-raw-load/39334 "2025-03-06T13:45:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MikeL](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mikel/32/27304_2.png) [@MikeL](https://forum.djangoproject.com/u/MikeL)\
**Post date:** [March 6, 2025, 1:45pm UTC](https://forum.djangoproject.com/t/orm-re-querying-rows-by-pk-when-iterating-queryset-after-raw-load/39334/1 "2025-03-06T13:45:41Z")

</div>

Hi and thanks for your help. I am loading ORM instances with the following technique:

all\_postop\_labs = PostOpLabFact\_v02.objects.raw(sql)

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.

Thanks for your help,  
Mike

---

<div class="post-metadata">

**Author:** ![MikeL](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mikel/32/27304_2.png) [@MikeL](https://forum.djangoproject.com/u/MikeL)\
**Post date:** [March 6, 2025, 2:41pm UTC](https://forum.djangoproject.com/t/orm-re-querying-rows-by-pk-when-iterating-queryset-after-raw-load/39334/2 "2025-03-06T14:41:21Z")

</div>

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.

Mike
