-2

In django i am trying to understand prefetch:

I have two for loop scenarios after prefetch

symbollist = SymbolList.objects.prefetch_related('some_related_name')[0:10]
for i in range(0,10):
    print(symbollist[i].some_related_name)

Now it calls sql N+1 times

where as

symbollist = SymbolList.objects.prefetch_related('some_related_name')[0:10]
for symbol in symbollist:
    print(symbol.some_related_name)

this will call only two sqls

Why so

Santhosh
  • 9,965
  • 20
  • 103
  • 243

1 Answers1

1

You are limiting symbol_list Queryset to 10 objects and caching related data for them using prefetch_related

but you are iterating through all the objects in database (notice count)

for i in range(0,symbollist.count()):
iklinac
  • 14,944
  • 4
  • 28
  • 30
  • even if i try to do `print(symbollist[0].some_related_name` it runs query – Santhosh Nov 10 '20 at 04:24
  • Show us minimal reproducible example by including models into question also why the second print in question is not like print(symbol.some_related_name) – iklinac Nov 10 '20 at 04:51