Django ORM querying nested many to many table efficiently?

  Kiến thức lập trình

SO lets say I am designing a db for cooking session models as below

from django.db import models

class Recipe(models.Model):
    name = models.CharField(max_length=255)
   
    def __str__(self):
        return self.name

class Step(models.Model):
    name = models.CharField(max_length=255)
    recipes = models.ManyToManyField(Recipe, related_name='steps')

    def __str__(self):
        return self.name

class CookingSession(models.Model):
    name = models.CharField(max_length=255)
    steps = models.ManyToManyField(Step, related_name='cooking_sessions')

    def __str__(self):
        return self.name

How can I use minimal number of queries (preferably one) to get all steps for a certain cooking session where each step should have the corresponding recipes if any.

cooking_sessions = (
            CookingSession.objects.annotate(
             
                step_list=ArrayAgg(
                    models.F(
                        "steps__name",
                    ),
                    distinct=True,
                ),
                recipe_list=ArrayAgg(models.F("steps__recipes__name")),
                
            )
           
        )

This is how the data looks like

[
    {
        'id': 1,
        'name': 'Italian Night',
        'step_list': ['Preparation', 'Cooking', 'Serving'],
        'recipe_list': ['Tomato Sauce', 'Pasta Dough', 'Spaghetti', 'Tomato Sauce', 'Garlic Bread']
    },
    ...
]

I would like the data to be like

{
    'id': 1,
    'name': 'Italian Night',
    'steps': [
        {
            'step_name': 'Preparation',
            'recipes': ['Tomato Sauce', 'Pasta Dough']
        },
        {
            'step_name': 'Cooking',
            'recipes': ['Spaghetti', 'Tomato Sauce']
        },
        {
            'step_name': 'Serving',
            'recipes': ['Garlic Bread']
        }
    ]
}

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT