我知道这个问题已经被问过了,但我不能真正理解答案背后的想法,因为我是编程的初学者,而且对我来说几乎一切都是新的。
我试图将每种配料的价格与其数量相乘,以获得其成本,然后将所有配料的成本相加,得到配方的final_cost,并在我的html模板上查看它。
我有一个查询,它返回来自DB的键和值的字典,现在im继续执行计算并在html上查看final_cost。
@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发布于 2019-03-15 06:40:50
在@amol和进一步研究的帮助下,我终于解决了自己的问题,这对我很有帮助。
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)发布于 2019-01-23 09:49:33
我没有一步一步地检查代码,但总体思路似乎是正确的。我看到的主要问题是,您正在公开模板recipe4.templates.newnew,但没有返回字典。
每当您公开一个模板时,控制器操作必须返回一个字典。字典的所有键将作为变量在模板中可用。
因此,如果希望在模板中访问return dict(final_cost=final_cost),则应该执行final_cost操作。
请参阅https://turbogears.readthedocs.io/en/latest/turbogears/templating.html#template-variables
https://stackoverflow.com/questions/54302460
复制相似问题