How to overwrite ORM method unlink from a custom module?
<p>I want to overwrite the <code>unlink</code> method of <code>stock.move</code> 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.</p>

<p>This is the original code:</p>

<pre><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)
</code></pre>

<p>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:</p>

<pre><code>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()
</code></pre>

<p>If I turn the last line (<code>super</code>) into <code>self.unlink()</code>, I get a <em>maximum recursion depth exceeded</em> error.</p>

<p>How can I manage my purpose from my custom module?</p>

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

<pre><code>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)
</code></pre>

<p>Another possibility would be a monkey patch on the original code.</p>

python python-2.7 openerp odoo-8