3

If I have two models in a many to many relationship like below:

class Topping(models.Model):
    name = models.CharField(max_length=50)

class Pizza(models.Model):
    name = models.CharField(max_length=50)
    toppings = models.ManyToManyField(Topping)

Can I create a queryset that will give me something like this?:

[
  {
    "name": "Hawaiian",
    "toppings": [
      {"name": "Pineapple"},
      {"name": "Canadian Bacon"},
      {"name": "Cheese"}
    ]
  },
  {
    "name": "Pepperoni Pizza",
    "toppings": [
      {"name": "Pepperoni"},
      {"name": "Cheese"}
    ]
  }
]

Can I create the nested object queryset in one line?

aero
  • 1,654
  • 1
  • 21
  • 31

1 Answers1

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.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139