0

I have two models like this:

class ItemType(models.Model):
type = models.CharField(max_length=100)

class Items(models.Model):
    item_type = models.ForeignKey(ItemType, on_delete=models.CASCADE)
    item_amount = models.FloatField()

now I want to get sum of item_amount according to item_type. How I can do this?

khanals
  • 21
  • 2
  • Does this answer your question? [How to execute a GROUP BY ... COUNT or SUM in Django ORM?](https://stackoverflow.com/questions/45547674/how-to-execute-a-group-by-count-or-sum-in-django-orm) – cabesuon Jun 19 '20 at 09:14

1 Answers1

0

Try something like this.

from django.db.models import Sum

result = Items.objects.values('item_type')
                           .order_by('item_type')
                           .annotate(total_amount=Sum('item_amount'))
Sami
  • 361
  • 1
  • 7