[Answered ]-Flattening multiple querysets that share the same name in Django

1๐Ÿ‘

โœ…

We can work with a single queryset:

from django.db.models import Q, Sum

data = (
    OrderElement.objects.filter(
        ordel_order_fk__ord_status=2,
        ordel_order_fk__ord_data_real__lte=datetime.now() + timedelta(days=14),
    )
    .values('ordel_nazwa')
    .annotate(
        total1=Sum(
            'ordel_ilosc',
            filter=Q(
                ordel_order_fk__ord_data_real__lte=datetime.now()
                + timedelta(days=7)
            ),
        ),
        total2=Sum('ordel_ilosc'),
    )
    .order_by('ordel_nazwa')
)

This will make dictionaries with the ordel_nazwa as key, and two extra keys total1 and total2 with the number of ordel_iloscs for the first seven days and the first 14 days respectively.

Leave a comment