turbogears2从查询行中乘以价格和成本

问题描述 投票:0回答:2

我知道这个问题已经被提出了,但我无法真正理解答案背后的想法,因为我是编程的初学者,而且几乎所有东西对我来说都是新的。

我试图将每种成分的价格乘以其数量以获得其成本,然后将所有成分的成本相加以获得配方的final_cost并在我的html模板上查看。

我有一个查询,它从数据库返回键和值的字典,现在我坚持计算并在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
python xhtml turbogears2
2个回答
0
投票

我没有逐步检查代码,但总的想法似乎是正确的。我看到的主要问题是你暴露模板recipe4.templates.newnew,但你没有返回字典。

无论何时公开模板,控制器操作都必须返回字典。字典的所有键都将在模板中作为变量提供。

所以你应该做return dict(final_cost=final_cost),如果你想在你的模板中访问final_cost

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


0
投票

我终于在@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)
© www.soinside.com 2019 - 2024. All rights reserved.