fifamaniac04
fifamaniac04

Reputation: 2383

web2py How to create computed field in DB

I am going to be adding fields to my Table schema in web2py using the db.py file...

I want to add three new fields, 2 datetime and 1 field to show the timespan of the other two fields...

Q: How can I define the 3rd field to automatically be populated from the difference of the two datetime values for a row?

Upvotes: 1

Views: 660

Answers (1)

Angel Alvarado
Angel Alvarado

Reputation: 26

Try something like the following:

>>> db.define_table('item',
                Field('unit_price','double'),
                Field('quantity','integer'),
                Field('total_price',
                      compute=lambda r: r['unit_price'] * r['quantity']))

>>> r = db.item.insert(unit_price=1.99, quantity=5)
>>> print r.total_price
9.95

See http://web2py.com/books/default/chapter/29/06/the-database-abstraction-layer#Computed-fields

Upvotes: 0

Related Questions