Computed fields

DAL fields may have a compute attribute. This must be a function (or lambda) that takes a Row object and returns a value for the field. When a new record is modified, including both insertions and updates, if a value for the field is not provided, web2py tries to compute from the other field values using the compute function. Here is an example:

  1. >>> db.define_table('item',
  2. ... Field('unit_price', 'double'),
  3. ... Field('quantity', 'integer'),
  4. ... Field('total_price',
  5. ... compute=lambda r: r['unit_price'] * r['quantity']))
  6. <Table item (id, unit_price, quantity, total_price)>
  7. >>> rid = db.item.insert(unit_price=1.99, quantity=5)
  8. >>> db.item[rid]
  9. <Row {'total_price': '9.95', 'unit_price': 1.99, 'id': 1L, 'quantity': 5L}>

Notice that the computed value is stored in the db and it is not computed on retrieval, as in the case of virtual fields, described next. Two typical applications of computed fields are:

  • in wiki applications, to store the processed input wiki text as HTML, to avoid re-processing on every request
  • for searching, to compute normalized values for a field, to be used for searching.

Computed fields are evaluated in the order in which they are defined in the table definition. A computed field can refer to previously defined computed fields (new after v 2.5.1)