Use computed, virtual, and filtered fields
masterpyDAL allows you to extend table behavior using computed fields, virtual fields, and common filters.
Computed vs Virtual Fields
- Computed Field: Calculated during
insertorupdateand physically stored in the database. Defined via thecomputeargument inField(). - Virtual Field: Calculated on-the-fly every time the field is accessed from a result set. It is not stored in the database and cannot be used in queries. Defined using
Field.Virtual().
Common Filters
You can attach a query to a table using _common_filter. Every Set (query) performed against that table will automatically include this filter. This is useful for implementing soft-delete or multi-tenant isolation.
- To bypass the common filter, use
db(query, ignore_common_filters=True).
Callbacks
You can hook into the lifecycle of a record using callbacks:
_before_insert_after_update_after_delete
Note: If a _before_* callback returns a truthy value, the operation is cancelled.
# Computed Field (Stored)
db.define_table("person",
Field("first"),
Field("last"),
Field("full", compute=lambda row: f"{row['first']} {row['last']}"),
)
# Virtual Field (Not stored, computed on access)
class PersonMethods:
def full(row):
return row.first + " " + row.last
db.person.full = Field.Virtual("full", lambda row: row.first + " " + row.last)
# Common Filter (e.g., for soft-delete)
db.thing._common_filter = lambda q: db.thing.deleted == False
# Callbacks
db.thing._before_insert.append(lambda fields: ...)
db.thing._after_update.append(lambda set, fields: ...)
db.thing._after_delete.append(lambda set: ...)