0

I can sum all payments for each Klient. But I need to know sum each type of payment.

Here are my models:

class Klient(models.Model):
    name = models.CharField(max_length=30)
    surname = models.CharField(max_length=30)
class Platba(models.Model):
    PAYMENT = 'P'
    GIFT = 'G'
    TYPE = [
        (PAYMENT, 'Patment'),
        (GIFT, 'Gift'),
    ]


    when = models.DateField()
    ammount = models.DecimalField(max_digits=10, decimal_places=2)
    klient = models.ForeignKey(
        Klient, 
        on_delete=models.CASCADE,
        related_name="payments"
    )
    type = models.CharField(
        'Kind of payments',
        max_length=1,
        choices=TYPE,
        default=PAYMENT,
    )

here is annotate for each klient and summing all payments, then print

all = Klient.objects.annotate(Sum("payments__ammount"))

for k in all:
     print(k, " -> ", k.payments__ammount__sum)

but I would like to get sum for each TYPE of Platba. so I can accesss like k.payments_p for Platba.PAYMENT and k.payments_g for Platba.GIFT

if I do

Klient.objects.values("id", "payments__type").annotate(Sum("payments__ammount"))

then I get two rows for each klient and that is not what I want.

thanks for help or tip

janci
  • 49
  • 6

1 Answers1

0

aha, I should do more reading manual ;-) it is conditional-aggregation what I need

and also I did find this answer helpfull, thanks

janci
  • 49
  • 6