1

Here's my model:

class Product:
  name = models.CharField(max_length=80)
  price = models.FloatField()
  category = models.CharField(max_length=40)
class ProductInventory:
  inventory = models.IntegerField()
  product = models.OneToOneField(Product, on_delete=models.RESTRICT)

and here's raw sql of what I want to achieve but how do I write this in django ORM?

SELECT product.category, SUM(price) * SUM(product_inventory.inventory) 
FROM product LEFT JOIN product_inventory 
ON product.id=product_inventory.product_id group by product.category;

Thank you.

1 Answer 1

2

You can try by using Sum in annotate and make a dummy field of name sum_product and pass it in values like this. Hope this will work for you.

from django.db.models import Sum

Product.objects.annotate(sum_product=Sum('price') * Sum('productinventory__inventory')).values('category', 'sum_product')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.