Re: Reduce number of sql calls to database

12 views
Skip to first unread message

Larry Martell

unread,
Jun 2, 2015, 12:10:39 PM6/2/15
to django...@googlegroups.com
On Tue, Jun 2, 2015 at 11:48 AM, Cherie Pun <cherie...@gmail.com> wrote:
> Hi,
>
> I am new to Django and I am trying to reduce the number of calls to database
> as it's slowing down the app. I am performing iteration over the queryset
> and I used django_debug_toolbar to check the number of queries made, and the
> number is huge. It looks like django is making a query call to the db in
> each iteration. Is there a way to make it only send one query and then store
> the result locally and iterate over it?
>
> Code:
> for level_id in levels_id:
> levels.append(get_object_or_404(Level, id=level_id))
>
> I have been trying out this code, but it seems that the number of sql
> queries is still the same.
> levels_dict = Level.objects.values('id', 'name')
> for level_id in levels_id:
> levels.append(levels_dict.get(id=level_id).get('name'))
>
> I am using the same pattern in a few places to get data from each of the
> object in the queryset, is there a way to improve the performance? I am
> happy to provide any missing information. Cheers!

How about this:

Levels.objects.filter(id__in= levels_id)
Reply all
Reply to author
Forward
0 new messages