計算されたフィールド

□未翻訳

□翻訳中

■翻訳完了(細田謙二)

■レビュー(Omi Chiba)

計算されたフィールド

DALのフィールドはcomputeフィールドを持つことがあります。これは、Rowオブジェクトをとり、そのフィールドに対する値を返す関数(またはラムダ)でなければなりません。新規のレコードが挿入や更新などで変更されるとき、そのフィールドに対する値が用意されていない場合、web2pyはcompute関数を用いて他のフィールドの値から計算しようとします。以下がその例です。

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.

2.

3.

4.

5.

6.

7.

8.

>>> 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

なお、計算された値はdbに格納され、後述する仮想フィールドの場合のように再取得時に計算されることはありません。2つの典型的な計算されたフィールドの活用方法があります:

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 later. Two typical applications of computed fields are:

  • wikiアプリケーションにおいて、HTMLに加工されたwikiの入力テキストを、リクエスト毎の加工を避けるために保存する

  • 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.