How do I filter on related objects that's fetched by prefetch_related without executing additional SQL queries?

Viewed 17

The below snippet is from Django doc: https://docs.djangoproject.com/en/4.1/ref/models/querysets/

>>> pizzas = Pizza.objects.prefetch_related('toppings')
>>> [list(pizza.toppings.filter(spicy=True)) for pizza in pizzas]

The second line executes additional SQL queries. Is there a Django native way of writing the above that filters in memory instead of executing SQL against db?

alternatively I can just write this without generating more SQL queries:


[[topping for topping in pizza.toppings if topping.spicy == True] for pizza in pizzas]
0 Answers
Related