On Sunday, January 13, 2019 at 10:24:03 AM UTC-5, mostwanted wrote:
>
> How can achieve decremental subtraction of a value in a database field?
>
> *MODEL CODE*
>
> db.define_table('fuelLogging',
>                 Field('Quantity', 'integer', requires=IS_NOT_EMPTY()),
>                 Field('Rate', 'integer', requires=IS_NOT_EMPTY()),
>                 Field('Total', compute=lambda r:r['Quantity']*r['Rate']),
>                 Field('ODO_Reading', 'integer', requires=IS_NOT_EMPTY()),
> *                Field('Delta', compute=lambda 
> r:r['ODO_Reading']-r['ODO_Reading'], requires=IS_NOT_EMPTY()),*
>                 Field('Fuel_Usage', compute=lambda r: r['Delta']/r[
> 'Quantity']))
> To get the delta field i have to subtract the previously entered 
> ODO_Reading value from the newly entered ODO_Reading value but what i have 
> done here is not working, any suggestions?
>

To use an existing field value in a query, you can use the field object 
itself (i.e., db.fuelLogging.ODO_Reading). However, for the DAL to treat 
the expression as an Expression object, the field object must come first, 
so you cannot do r.ODO_Reading - db.fuelLogging.ODO_Reading. You must 
instead use (db.fuelLogging.ODO_Reading * -1) + r.ODO_Reading.

Another problem you will have is that the compute function will not work on 
inserts because there is no value in the ODO_Reading field in that case. A 
workaround is to set the compute attribute conditionally only on updates:

def fuelLogging_before_update(*args, **kwargs):
    db.fuelLogging.compute = lambda r: (db.fuelLogging.ODO_Reading * -1) + r
.ODO_Reading

db.define_table('fuelLogging',
    Field('ODO_Reading', 'integer'),
    Field('Delta', 'integer', default=0),
    before_update=fuelLogging_before_update)

Anthony

-- 
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
--- 
You received this message because you are subscribed to the Google Groups 
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to