Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Django's ORM return a nested object queryset?

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?

like image 279
aero Avatar asked Jun 01 '26 19:06

aero


1 Answers

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.

like image 90
Moses Koledoye Avatar answered Jun 03 '26 13:06

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!