db.define_table('Product',
Field('name',),
Field('price', 'decimal(10,2)'),
Field('quantity', 'integer'),
Field('quantity_sold', 'integer'), # this could be virtual - but then it does not play with queries...
)
I want to refresh quantity_sold after each Purchase (insert/update/delete)
but after delete I'd like to still access which product it has been?
if I do it before delete, the purchace is still there - and my aggregate function sums it (though I need it gone) ...
db.define_table('Purchase',
Field('product', db.Product),
Field('quantity', 'integer'),
)
def update_Product_quantity_from_Purchase( purchase ):
q_sum = db.Purchase.quantity.sum()
quantity_sold = db(db.Purchase.product== purchase.product ).select(q_sum).first()[q_sum] or 0
db.Product[purchase.product].update_record( quantity_sold=quantity_sold )
db.Pardavimai._after_insert.append( lambda f,id: update_Product_quantity_from_Purchase(f) )
db.Pardavimai._after_update.append( lambda s,f: update_Product_quantity_from_Purchase(s.select()[0]) )
db.Pardavimai._after_delete.append( lambda s: update_Product_quantity_from_Purchase(s.select()[0]) ) #ERR
***
Ha, while writing I came up with workaround - _before_delete
I add extra parameter to my update_Product... function, which tells that purchase stuff should be subtracted in advance (as it will be detelted)
def update_Product_quantity_from_Purchase( purchase, deleting=False ):
...
if deleting:
quantity_sold -= purchace.quantity
db.Product[purchase.product].update_record( quantity_sold=quantity_sold )
db.Pardavimai._before_delete.append( lambda s: update_Product_quantity_from_Purchase(s.select()[0], True) ) #OK
***
ps.: Maybe similar functionality could be extended for "compute'd" field?
If it knew what foreign tables&fields it depends on, the triggers/callbacks could be added automatically?