4👍
✅
Django currently supports no query method for returning such objects directly from a query, however, you can use a prefetch_related
to get the toppings
for the pizza
objects, and then build your nested object in python:
pizzas = Pizza.objects.prefetch_related('toppings')
nested_obj = [{"name": pizza.name, "toppings": [{"name": topping.name} for topping in pizza.toppings.all()]} for pizza in pizzas]
You still get to use one query.
Source:stackexchange.com