0

I am using Django ORM to query a database called Product having column name price(Decimal) and stock_units(int). I want to Multiply both of the columns and get the accumulated summation.

report = Product.objects.filter(stock_units__gte=1).aggregate(Count('name'), Sum('stock_units'), Sum(F('price')*F('stock_units')))

I expect the output to be {

 "Total product Sold ": {
        "name__count": 2,
        "stock_units__sum": 844,
        "Total amount": 84400

    }
}

But it through an error:

TypeError: 'F' object is not subscriptable

Astik Anand
  • 12,757
  • 9
  • 41
  • 51
Umar Hayat
  • 4,300
  • 1
  • 12
  • 27
  • The error wants to say that the object cannot contain an anothor object. https://stackoverflow.com/questions/216972/in-python-what-does-it-mean-if-an-object-is-subscriptable-or-not/216980#216980 see this for more details. – Eternal May 24 '19 at 07:15
  • But I need a clear solution in Django. – Umar Hayat May 24 '19 at 07:17

1 Answers1

1

First use annotate() to multiply price and stock units then use this annotation in aggregate(). Like this:

report = Product.objects.filter(stock_units__gte=1)\
    .annotate(value=F('price') * F('stock_units'))\
    .aggregate(
        count=Count('name'), 
        stock=Sum('stock_units'),
        total_value=Sum('value')
     )
Borut
  • 3,304
  • 2
  • 12
  • 18