python - Optimizing django select queries for Generic model -
i have generic model "emaileditem" referencing model "item".
i loop on list of items , print time email sent.
for doing:
items = item.objects.all() item in items: emaileditem = emaileditem.objects.get(object_id=item.item_id) print emaileditem.created
the problem routine needs run pretty , takes lot of time select on database each item.
is there better way so?
thanks lot,
edit answering commenet
create list of ids values_list
, query __in
items = item.objects.all() dict_of_emailteditems = {i.object_id: in emaileditem.objects.filter(object_id__in=items.values_list('item_id', flat=true))} item in items: emaileditem = dict_of_emailteditems[item.id] print emaileditem.created
this generate 2 queries db instead of 1 + n, n number of items
Comments
Post a Comment