0

I have a queryset with complex relations, and I need to retrieve specific data from it using aggregations. My data structure looks like this:

filters = [{
        'colors': [
            {'black': '#000000'},
            {'white': '#111111'}
        ]
    },
    {
        'categories': [
            {
                'Digital': [
                    {
                        'mobile': [
                            {'Apple': ['first_phone', 'second_phone']},
                            {'Android': ['first_phone', 'second_phone']}
                        ]
                    }
                ]
            }
        ]
    }
]

The 'categories' field has a three-level parent-children structure. I want to avoid making multiple queries since the original queryset is quite heavy.

I have attempted the following aggregation, which works fine for the first level:

queryset.aggregate(
    colors=ArrayAgg(
        {F('packs__colors__title'): F("packs__colors__hex_code")},
        distinct=True,
    ),
    categories=ArrayAgg(
        {
            F('categories__title'): {
                F("categories__parent__title"): {
                    F("categories__parent__parent__title")
                }
            }
        },
        distinct=True
    )
)

However, I'm not sure how to handle the aggregation for the nested levels of the 'categories' field. Can you please provide guidance on how to accomplish this?

scaryhamid
  • 345
  • 2
  • 9

0 Answers0