Odoo one2many & many2many tips

One2many, Many2many fields odoo

Case 1

Many2many relationship with same co-model on the same entity in Odoo.

as we know the basic principal of many2many field is its create another table/model in database so when there is two fields we have to enter relation table/model name seperate for both fields.

from odoo import models, fields

class TrainingSession(models.Model):
_name = 'training.session'
_description = 'Training Session Model'

name = fields.Char(string='Session Name')
attendees = fields.Many2many(comodel_name='res.users', relation='training_attendees_rel', column1='session_id', column2='user_id', string='Attendees')
moderators = fields.Many2many(comodel_name='res.users', relation='training_moderators_rel', column1='session_id', column2='user_id', string='Moderators')

Case 2

Many2many field record update while working on py code logic 

setting many2many field of attendees 

object.attendees = [(6, 0, user_list)] 
for set attendees empty
object.attendees = [(6, 0, [])]

Case 3

suppose we need to have a domain based on many2many fields but when we try it using py file its cause issue suppose its not depend on field selection so better in this case use many2many as a computed field and use it in the domain to filter the records.

but we achieve below by char field as well using computed char field and then reference it in domain may be better option then below like storing list of ids of the records that will refer in domain to shows only those records

attendees = fields.Many2many('res.users', store=True, compute='_get_attendees_list')
def _get_attendees_list(self):
for object in self:
#set attendees based on condition suppose if something
object.attendees = [(6, 0, user_list)]
#else define empty as well
object.attendees = [(6, 0, [])]

Case 4

Record creation of one2many 

suppose result_line_ids is one2many field and we have to fill this with py code onchange of parent field lab_order

def onchange_order(self):
for record in self:
# set record to none for one2many field
self.result_line_ids = [(5,)]
if record.lab_order and record.lab_order.order_line:
for line in record.lab_order.order_line:
       self.result_line_ids |= self.result_line_ids.new({'test_name': line.product_id,'description': line.name,})

# Odoo
odoo server migration
--> AlhadiTech