Chris
Chris

Reputation: 6095

How do I make a computed field based on multiple other fields in web2py?

I have a computed field in my db model as follows:

Field('computed_field', compute=lambda(page): compute_this_field(page)),

What I recently discovered is that compute only passes the fields of page that are changed during an update call. If my function compute_this_field requires other fields to finish its computation, it doesn't get them.

What's the best way to get around this limitation?

Upvotes: 1

Views: 891

Answers (1)

Anthony
Anthony

Reputation: 25536

The problem is that if you are updating multiple records, and the records don't have the same values on the non-updated fields, there would be no way to calculate a single computed value for all the updated records -- each record would need its own computed value, which could not be handled in a single update. If you want the computed value to be updated, you should pass in all the values it needs for the computation (even if some of them are not changing). One way to do this is as follows:

query = db.mytable.id == [some id]
row = db(query).select().first()
row.update(field1=newvalue1)
db(query).update(**row.as_dict())

The above first extracts a single record (i.e., Row object), makes the changes to the Row object, and then passes the entire Row object (which includes all the fields) to the .update() method.

Upvotes: 1

Related Questions