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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Moses, that is what I was looking for!
It's 2019, is this still true?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.