Home > Software design >  Calculate Sub Table Django
Calculate Sub Table Django

Time:11-22

I'm new on Django, I try to calculate sub table of related table. I have two models Transaction and Detail. here is my models:

    class Transaction(models.Model):
        id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
        code = models.CharField(max_length=50)

    class Detail(models.Model):
        id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
        transaction = models.ForeignKey(Transaction, related_name='details', on_delete=models.CASCADE)
        qty = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False)
        price = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False)

I want to get sum of calculation (Detail.qty * Detail.price) on a single query like this:

datas = Transaction.objects.all().annotate(sum=sum(qty*price))

How to do that on Django ORM?

CodePudding user response:

You can achieve this with a combination usage of F and Sum in Django.

The detail__ allows you to access foreign key Detail

from django.db.models import F, Sum

datas = Transaction.objects.annotate(sum=Sum(F('detail__qty')* F('detail__price')))
  • Related