Megha Sirisilla
Megha Sirisilla

Reputation: 151

How to delete records in a table with many2one field if the other table with its one2many field is deleted?

I'm deleting some records in a table but few one2many fields of in this table are in relation with other tables(many2one). Can you all help me how to do it with a query? I want to delete the many2one field records also.

delete from manpower_estimate where manpower_estimate_line  IN (select id from res_scheduledjobs where contract_start_date < '2014-12-31' and contract_end_date < '2014-12-31')

This is what I'm doing. res_scheduledjobs is the table with one2many field and manpower_estimate is the table with its many2one field

Upvotes: 0

Views: 2533

Answers (1)

gdaramouskas
gdaramouskas

Reputation: 3747

Check the docstring of the Many2one class in odoo/fields.py if you are on Odoo v10 or openerp/fields.py for previous versions around line 1840.

When you create a Many2one field you can use the ondelete argument to signify to the ORM what will happen when a record is deleted.

:param ondelete: what to do when the referred record is deleted; possible values are: 'set null', 'restrict', 'cascade'

What you are looking for is cascade.

You might want to avoid removing relations using sql because it can break your database (since you are not using ORM). Plus, if you do remove them using sql then you need to keep in mind that other tables might hold references.

So, redefine the field with ondelete="cascade" and proceed deleting.

Upvotes: 1

Related Questions