Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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
–
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')
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.