On Thursday, May 17, 2012 7:46:28 AM UTC-4, bioform wrote:
>
> Hello.
> I have two models: "order (fields: id,cost)" and "order_item (fields: id, 
> order, price, quantity)".
> "order_item.order" looks like:
> Field('order', db.order)
>
>
> i'll try to add "total_price" field to "order" table:
> Field('total_price', 'integer' ,compute=lambda row: calc(row))
>

No need for a lambda above -- just do compute=calc, since calc is already 
callable.
 

> where "calc(row)" looks like:
> def calc(order):
>   result = 0
>   for item in order.order_item.select()
>     result += item.price
>   return result
>

Note, the Row object is passed to the compute function, so in your calc() 
function, "order" is actually the Row object of the record being entered 
into the order table. The order table doesn't have an order_item field, so 
order.order_item doesn't make sense. Even if that was a field, the 
.select() method cannot be called on a field -- it must be called on a DAL 
Set object. (Also missing the colon at the end of the for statement.) You'd 
probably want something more like this:

    for item in db(db.order_item.order == order.id).select():

However, when a record is first inserted into the order table, the calc 
function won't have anything to calculate, because there won't yet be any 
records in the order_item table associated with the new order. You might 
have to update the db.order record after the db.order_item records have 
been added. Or maybe a virtual field would be better here.

Anthony

Reply via email to