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!