Search code examples
pythonxhtmlturbogears2

turbogears2 multiply price and cost from rows of query


I know this question has been asked already, but i couldn't really grasp the idea behind the answers as i am a beginner in programming and pretty much everything seems new to me.

I am trying to multiply the price of each ingredient with its quantity to get its cost, then sum the costs of all the ingredients to get the final_cost of the recipe and view it on my html template.

I have a query which returns a dictionary of keys and values from the DB and now im stuck with the calculations and viewing the final_cost on html

@expose('recipe4.templates.newnew')
    def getTotalCost(self):
        i = Ingredient
        ic = Ingredient_Cost
        ri = Recipe_Info
        r = Recipe
        val = DBSession.query(i.ingredient_name, ic.Unit_of_Measure, ri.quantity, ic.price_K, ic.updated_at).filter \
        (r.recipe_name == "pancake",
         r.recipe_id == ri.recipe_id,
         ri.ingredient_id == i.ingredient_id,
         i.ingredient_id == ic.ingredient_id)

        dict(entries=val)
        final_cost=0
        for k,v in entries:
            price=entries.price_K
            qty=entries.quantity
            cost=price*qty
            final_cost+=cost

        return final_cost

Solution

  • I finally solved my own problem with some help from @amol and further research and it works for me.

    sub_cost=[ ]    
    final_cost=[ ]  
    for k in val:  #iterate through each row of tuples in the returned db object
        for v in k:  #iterate through each values of individual tuples
            price=k[3] #position of price in tuple
            qty=k[4]
            cost=price*qty
            sub_cost.append(cost)
            break #breaks the loop
    final_cost.append(sum(sub_cost))
    return dict(final_cost=final_cost)