pony icon indicating copy to clipboard operation
pony copied to clipboard

Comparing new object values with existing values in .before_update() hooks?

Open wshyang opened this issue 5 years ago • 3 comments

This is not so much a bug report but more of a query as it wasn't quite clear from the docs, sorry if it is in the wrong place :)

I am just wondering if it is possible to perform validation / comparisons between the new incoming object values against the existing object values stored in the database prior to saving?

Also, what's the convention to abort the save of a record due to invalid values? For instance, in RoR we have something like a system of performing column/object validations. Does a similar system exist for Pony?

wshyang avatar Mar 07 '19 00:03 wshyang

I was wondering the same. I needed to auto-hash a password field in a user model. How can I know if the password has changed?

ghost avatar Nov 10 '19 16:11 ghost

Couldn't you just load the original object from the database and compare that against the new values?

LaundroMat avatar May 20 '22 11:05 LaundroMat

Hello, Inside before_update you can use something like this

for attr, bit_value in obj._bits_.items():
    if attr.reverse and isinstance(attr, Set):
        continue
    if bit_value & obj._wbits_:
        old_value = obj._dbvals_.get(attr)
        new_value = obj._vals_.get(attr)

Where obj is the object itself. if bit_value & obj._wbits_ actually means if attribute value was changed. If you don't care were they changed or not or want to compare your own way (which will be slower) - remove this condition.

sashaaero avatar May 20 '22 12:05 sashaaero