0

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
Cami
  • 15
  • 7

2 Answers2

0

I didn't check the code step by step, but the general idea seems correct. The main problem that I see is that you are exposing template recipe4.templates.newnew but you are not returning a dictionary.

Whenever you expose a template, the controller action must return a dictionary. All the keys of the dictionary will be available in the template as variables.

So you should do return dict(final_cost=final_cost) if you want to have final_cost accessible in your template.

See https://turbogears.readthedocs.io/en/latest/turbogears/templating.html#template-variables

amol
  • 1,771
  • 1
  • 11
  • 15
0

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)
Cami
  • 15
  • 7