How to force remove records form lines in odoo?

Question:

something wrong happened in account moves as adding an analytic account to journal items of vendor bills and I need to loop on all lines in account moves and remove the analytic account from all lines by this bit of code

class NewModule(models.Model):
_inherit = 'account.move'

def analytic(self):
    all=self.env['account.move'].search([('type','=','in_invoice')])
    ana=all.line_ids.mapped('analytic_account_id')
    ana.unlink()

but when this method run I get this error “The operation cannot be completed: another model requires the record being deleted. If possible, archive it instead.
Model: Analytic Line (account.analytic.line), Constraint: account_analytic_line_account_id_fkey”
as image below
enter image description here

otherwise if tried to remove the analytic account for UI it removed without any issues but there is too many bills to do it manually

any help will be appreciated

Asked By: Mohamed Fouad

||

Answers:

You are trying to delete analytic_account objects.
You need to remove Many2Many connections to the analytic_account objects.

all=self.env['account.move'].search([('type','=','in_invoice')])
all.write({'analytic_account_id':[(5, 0, 0)]})

It should be like that. But I did not test it.

Answered By: Paxmees

it’s worked for me with this method

def analytic(self):    
self.env['account.move'].search([('type', 'in', ('out_invoice', 'in_invoice'))]).line_ids.write({'analytic_account_id':[(5, 0, 0)]})
Answered By: Mohamed Fouad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.