Home > front end >  Django SUM 2 Column with Different Condition
Django SUM 2 Column with Different Condition

Time:11-11

In Django how to sum 2 column with different condition, how i try to sum column amount with condition trx=2 and amount with condition trx=3

reportusage = (Invoices.objects
                            .annotate(month=ExtractMonth('datetime'))
                            .values('month')
                            .annotate(total=Sum('amount').filter(trx=2)   Sum('amount').filter(trx=3), product=F('tenant'))
                            .order_by())

CodePudding user response:

To apply a filter on the column in annotation, you may try this

reportusage = (Invoices.objects
                            .annotate(month=ExtractMonth('datetime'))
                            .values('month')
                            .annotate(total=Sum('amount', filter=Q(trx=3))   Sum('amount', filter=Q(trx=3)), product=F('tenant'))
                            .order_by())
  • Related