Chaban33
Chaban33

Reputation: 1382

Calculate two fields with on function

I have this function that calculates qty_incoming, but there is an outgoing_qty field that I want to calculate with the same function and not to create separate function for its calculation. how can I do this?

 _columns = {
            '
            'incoming_qty': fields.function(_product_inc_out_qty, type='float',
                digits_compute=dp.get_precision('Product Unit of Measure'),
                string='Incoming'
            ),
            'outgoing_qty': fields.function(_product_inc_out_qty, type='float',
                digits_compute=dp.get_precision('Product Unit of Measure'),
                string='Outgoing'
            ),
        }

function:

def _product_inc_out_qty(self, cr, uid, ids, field_names=None, arg=False, context=None):
        if context is None:
            context = {}

        res = {}
        for move_id in ids:
            move = self.browse(cr, uid, move_id, context=context)

            res[move.id] = move.product_id.incoming_qty or 0.0
        return res

if I do something like this, then I get error TypeError: float() argument must be a string or a number

  def _product_inc_out_qty(self, cr, uid, ids, field_names=None, arg=False, context=None):
        if context is None:
            context = {}

        res = {}
        vals = {
            'outgoing_qty': 0.0,
            'incoming_qty': 0.0,


        }
        for move_id in ids:
            move = self.browse(cr, uid, move_id, context=context)
            vals['outgoing_qty'] = move.product_id.qty_available or 0.0
            vals['incoming_qty'] = move.product_id.incoming_qty or 0.0
            res[move.id] = vals

        return res

Upvotes: 1

Views: 81

Answers (2)

Chaban33
Chaban33

Reputation: 1382

The problem in my code was that in old API if you want to return values for more than 1 field you need to add multi="any_string" to your field

So my fields should look like this

'incoming_qty': fields.function(_product_inc_out_qty, type='float',
                digits_compute=dp.get_precision('Product Unit of Measure'),
                multi='all',
                string='Incoming'
            ),

Upvotes: 0

Kenly
Kenly

Reputation: 26748

Multiple fields can be computed at the same time by the same method, just use the same method on all fields and set all of them:

discount_value = fields.Float(compute='_apply_discount')
total = fields.Float(compute='_apply_discount')

@depends('value', 'discount')
def _apply_discount(self):
    for record in self:
        # compute actual discount from discount percentage
        discount = record.value * record.discount
        record.discount_value = discount
        record.total = record.value - discount

You can find an example in old api at sale_order

Upvotes: 1

Related Questions