2
How do I calculate the subtotal and total per store (store) in the view to play the results in the template? In this case I’m using lists.
def quotation_list(request):
stores = list(Store.objects.all())
products = list(Product.objects.all())
# indice
index_store = {store.id: index for index, store in enumerate(stores)}
index_product = {product.id: index for index,
product in enumerate(products)}
# dados para o template
cabecalho = ["Lojas"] + [store.store for store in stores]
linhas = [([product.product] + [None for store in stores])
for product in products]
for pev in Quotation.objects.all():
total = pev.price * pev.quantity
linhas[index_product[pev.product_id]][index_store[pev.store_id] +
1] = (pev.price, pev.quantity, total, pev.store, pev.product)
# retorna o menor preço de cada produto
# a quantidade, total e loja também estão nesta lista
mais_barato = []
for linha in linhas:
mais_barato.append(min(linha[1:]))
# destaca os menores preços no template
mb = 0
if request.GET.get('mais_barato', False):
mb = 1
# mostra somente os menores preços
smb = 0
if request.GET.get('somente_mais_barato', False):
smb = 1
Notice that here I order the list by shop.
# mostra os produtos mais baratos, a quantidade e o total
bqt = 0
if request.GET.get('quantidade_e_total', False):
mais_barato = sorted(mais_barato,
key=lambda store: str(store[3])) # sort by store
bqt = 1
context = {
'cabecalho': cabecalho,
'linhas_mais_barato': zip(linhas, mais_barato),
'mb': mb,
'smb': smb,
'bqt': bqt,
}
return render(request, 'core/quotation_list.html', context)
I tried something similar to this here
https://stackoverflow.com/a/22366344/802542
but it didn’t work out.
@mgibsonbr goes who is your Marcelo Gibson. :)
– Regis Santos
I don’t understand your ordering. Are you ordering by shop, simply? Like, in alphabetical order or something? If that’s the case, it would be easier to do it right at the beginning, i.e.
stores = list(Store.objects.all().order_by("store"))
. Now, if what you want is to reorder the columns so that the stores with the cheapest total appear in front, this is a little bit more complicated (because you would need to maintaincabecalho
andlinhas
consistent during this ordering).– mgibsonbr