Python add when entries have the same name
I have a model with the registered sales of a publishing house.with the following code, I can get the name of the book and the quantity the client bought:
a=Sale.objects.all()
for b in a:
print(str(b.book) + ' ' + str(b.quantity))
So I get something like this:
Del mismo modo en el sentido contrario 15
Sobre el horror 1
Del mismo modo en el sentido contrario 5
Del mismo modo en el sentido contrario 2
Un lápiz labial para una momia 1
La cólera en los tiempos del amor 3
La cólera en los tiempos del amor 1
La cólera en los tiempos del amor 1
El tambor encantado 1
What I need now is a loop so every entry that has the same book name, sum or add that quantity number. Any ideas on how to accomplish this?
Solution 1:
For Django, to do this entirely in the database, it sounds like you want an aggregation using .values()
:
for book, total_sales in Sale.objects.values('book').annotate(total_sales=Sum('quantity')).values_list('book', 'total_sales'):
print(book, total_sales)
The general case, if this wasn't only about Django, is to use a collections.Counter
:
books_sold = collections.Counter()
for sale in Sale.objects.all():
books_sold[str(sale.book)] += b.quantity
for book, quantity in books_sold.items():
print(book, quantity)