views:

100

answers:

1

In a Django view I'm doing something like this..

lists = Stuff.objects.exclude(model2=None)
for alist in lists:                        
     if alist.model2.model3.id == target_id:
          addSomeStuff

The slowness comes from going from model (database row) to model in the if statement.
This actually takes nearly a second to run when lists has only about 486 items in it. I believe this is slow because 486*2+1 db lookups are being performed. If I where to rewrite this so it grabbed the whole model2 table and model3 table at once, and then just filter through there, it would be 3 db hits, I believe it would go much faster. That would destroy all the niceness django makes though.

Is there any way to convince django to do some sort of bulk data lookup like this?

+4  A: 

Do

Stuff.objects.exclude(model2=None).select_related('model2')

and do

if alist.model2.model3_id == target_id

These should cut it to just 1 SQL query.

Alex Gaynor