This question has been flagged
2 Replies
2266 Views

My question is:
I am automatically tagging customers depending on the analytic account from sales orders. Does a .write() always write on the record even when the value is already there? Should I be doing a check with an if statement to see if the tag has already been set? If so, how do I check that? I tried a few things and couldn't figure it out.

*Edit: I should have noted that my code is working well but I'm just wondering if I should be checking if the category_id value is already there before the write happens and if so how to check. I am still very much in the  learning stage of Odoo development*

My code:

contact_tag_id = None
project_id = record.project_id.id
project_id_name = record.project_id.name
partner_id = record.partner_id.commercial_partner_id.id

if project_id == 44:
        contact_tag_id = 4
if project_id == 49:
        contact_tag_id = 6
if project_id == 48:
        contact_tag_id = 3
#Add the tag to contact
if contact_tag_id != None:
        project_id = contact_tag_id
        env['res.partner'].search([('id','=',partner_id)]).sudo().write({'category_id': [(4, contact_tag_id)]})

Avatar
Discard

i haven't known your model and type of variable, so i can't fix your code

Best Answer

If the category_id is many2many field on partner master, then you can try the following code.

partner_ids = self.env['res.partner'].search([('id','=',partner_id)])

if partner_ids:

    category_ids = [contact_tag_id]+partner_ids.category_id.ids

    partner_ids.sudo().write({'category_id': [(6, 0, category_ids)]})

Avatar
Discard
Author

Thanks for your reply. See my edit to the question. My code is already working well from the start but how do I check if the ID that I am adding to category_id is already there before the write happens?

partner_ids.category_id.ids

Author

So something like this?

partner_ids = self.env['res.partner'].search([('id','=',partner_id)])

if contact_tag_id not in partner_ids.category_id.ids

#Add the tag to contact

if contact_tag_id != None:

project_id = contact_tag_id

env['res.partner'].search([('id','=',partner_id)]).sudo().write({'category_id': [(4, contact_tag_id)]})

yes your right