MichaelS
MichaelS

Reputation: 341

Django - multiply two queryset

I have two models:

class Product(models.Model):
    name = models.CharField()
    price = models.FloatField()

class Sales(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantité = models.IntegerField()

I defined two querysets:

Product = Product.objects.all()
Sales = Sales.objects.all()

How can I have a queryset of the total amount sold by each product?

Something like - product x has y amount of sales

Upvotes: 1

Views: 161

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can annotate the Product queryset with:

from django.db.models import F, Sum

Product.objects.annotate(
    total_sold=F('Price') * Sum('sales__Quantité')
)

The Product objects that arise from this queryset will contain an extra attribute .total_sold that contains the price multiplied by the sum of the related Quantités of the related Sales objects.

Upvotes: 1

Related Questions