Search code examples
pythonpython-2.7odooodoo-8

How to overwrite ORM method unlink from a custom module?


I want to overwrite the unlink method of stock.move model. The reason is that I want to remove an OSV exception which warns about a forbidden action, and replace it with other message and other condition.

This is the original code:

def unlink(self, cr, uid, ids, context=None):
    context = context or {}
    for move in self.browse(cr, uid, ids, context=context):
        if move.state not in ('draft', 'cancel'):
            raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
    return super(stock_move, self).unlink(cr, uid, ids, context=context)

I have just realized that removing that message is complexer than I thought. This is my current code, which is checking my condition, but then checks the original one I want to avoid:

class StockMove(models.Model):
    _inherit = 'stock.move'

    @api.multi
    def unlink(self):
        for move in self:
            if move.lot_id and move.lot_id.any_unit_sold is True:
                raise Warning(_('You can only delete unsold moves.'))
        return super(StockMove, self).unlink()

If I turn the last line (super) into self.unlink(), I get a maximum recursion depth exceeded error.

How can I manage my purpose from my custom module?


Solution

  • Not using a super() call can have unexpected behaviour. You could call models.Model.unlink(), but that will skip all unlink() extensions for stock.move by other modules (even Odoo S.A. apps/modules). In your case it would be:

    class StockMove(models.Model):
        _inherit = 'stock.move'
    
        @api.multi
        def unlink(self):
            for move in self:
                if move.lot_id and move.lot_id.any_unit_sold is True:
                    raise Warning(_('You can only delete unsold moves.'))
            return models.Model.unlink(self)
    

    Another possibility would be a monkey patch on the original code.