4

I am trying to apply a constraint in Odoo 8. I have read its explanation and followed the examples:

Decorates a constraint checker. Each argument must be a field name used in the check. Invoked on the records on which one of the named fields has been modified. (from https://www.odoo.com/documentation/8.0/reference/orm.html)

This decorator will ensure that decorated function will be called on create, write, unlink operation. If a constraint is met the function should raise a openerp.exceptions.Warning with appropriate message. (from http://odoo-new-api-guide-line.readthedocs.io/en/latest/decorator.html)

But it is not working at all in my case. I made a constraint for stock.picking model which depends on state field (at the beginning it depended on picking_type_id, state and move_lines fields, but I changed that for simplifying the problem):

@api.one
@api.constrains('state')
def _check_lot_in_outgoing_picking(self):
    _logger.info('MY CONSTRAINT IS CALLED')
    if self.picking_type_id.code == 'outgoing' and \
        self.state not in ['draft', 'cancel'] and \
        any(not move.restrict_lot_id for move in self.move_lines):
         raise ValidationError(
             _('The lot is mandatory in outgoing pickings.')
         )

The problem is that the constraint is called when I create a new picking and no more times. If I mark as to do, confirm or transfer the picking, its state changes but the constraint is not called anymore.

Anything I miss about this? Can anyone help me, please?

Community
  • 1
  • 1
forvas
  • 9,801
  • 7
  • 62
  • 158

1 Answers1

1

Looks like the problem might be related to the fact that it is an old-style computed field. Simply overriding the state field and the _state_get method of the stock.picking model using new-style api seems to fix the issue and the constrains is called every state change.

class stock_picking(models.Model):
    _inherit = "stock.picking"

    @api.one
    @api.depends('move_lines', 'move_type', 'move_lines.state')
    def _state_get(self):
        self.state = super(stock_picking, self)._state_get(field_name='state', arg=None, context=self._context)[self.id]

    state = fields.Selection(compute=_state_get)

This workaround worked for me.

dgeorgiev
  • 919
  • 7
  • 22