Reduce number of calls to database

36 views
Skip to first unread message

Cherie Pun

unread,
Jun 2, 2015, 3:42:19 PM6/2/15
to django...@googlegroups.com
Hi,

I am new to Django and I am performing some iteration on a queryset. When I use django_debug_toolbar to look at the SQL usage, I realised that Django is actually calling the database once in each iteration. Is there a way to make it call the database only once and somehow store it locally so that I can iterate on it?

Code:
for level_id in levels_id:
   levels
.append(get_object_or_404(Level, id=level_id))


I am trying this modified code, but it seems that it's still calling the same number of times.

        levels_dict = repr(Level.objects.values('id', 'name'))
       
for level_id in levels_id:
            levels
.append(levels_dict.get(id=level_id).get('name'))

I am trying to use this pattern in quite a few places, where I want to get some data from a list of objects retrieved from the database and iterate over them.
I would be happy to provide any missing information.

Could anyone kindly help me out? Cheers!

Simon Charette

unread,
Jun 2, 2015, 4:07:49 PM6/2/15
to django...@googlegroups.com
Hi Cherie,

A `id__in` queryset lookup should issue a single query.

levels = Level.objects.filter(id__in=level_ids)

Cheers,
Simon

Cherie Pun

unread,
Jun 5, 2015, 7:32:53 AM6/5/15
to django...@googlegroups.com

Thanks! Would this still give 404 errors when a certain object does not exist?

kel...@ist-total.org

unread,
Jun 5, 2015, 7:53:48 AM6/5/15
to django...@googlegroups.com
On Fri Jun 5 08:32:52 2015 GMT+0100, Cherie Pun wrote:
>
> Thanks! Would this still give 404 errors when a certain object does not
> exist?

Nope, but if you really need to ensure all ids exist in the database, compare the length of your level_ids with levels.count()
Make sure there are no duplicates in the id list (e.g. use set(level_ids)).

If they differ raise Http404 manually.

--
Florian

Cherie Pun

unread,
Jun 5, 2015, 2:22:57 PM6/5/15
to django...@googlegroups.com, kel...@ist-total.org
Thanks!
Reply all
Reply to author
Forward
0 new messages