0

I have two models, TextMessage and Device, that are related many TextMessages to one Device.

from odoo import models, fields, api

class Device(models.Model):
    _name = 'device'
    _description = 'A model for storing all devices'

    name = fields.Char()
    iden = fields.Char()
    model_name = fields.Char()
    manufacturer = fields.Char()
    push_token = fields.Char()
    app_version = fields.Integer()
    icon = fields.Char()
    has_sms = fields.Char()
    text_message_ids = fields.One2many("text_message", "device_id", string="Text Messages")
from odoo import models, fields, api

class TextMessage(models.Model):
    _name = 'text_message'
    _description = 'Text Messages'

    name = fields.Char()
    message_text = fields.Text()
    pb_response = fields.Text()
    target_number = fields.Char()
    device_id = fields.Many2one('device', 'Device', required=True)
    

    @api.model
    @api.depends("device_id")
    def create(self, values):
        print("values['device_id']",values["device_id"])
        print("self.device_id",self.device_id.iden)
        for rec in self.device_id:
            print("Device ID",rec.iden)
            values['pb_response'] = rec.device_id.iden
        
        return super().create(values) 

In the create method of TextMessage, I want to retrieve the value of the iden attribute of the Device model.

The print statements in TextMessage.create print:

values['device_id'] 1

self.device_id False

The print statement in the loop prints nothing.

kpg
  • 7,644
  • 6
  • 34
  • 67

1 Answers1

0

You can't access self before creating the record so it will be false.

You can write the create method in two ways:

Create the record first and then get the iden value:

@api.model
def create(self, values):
    res = super().create(values)
    res.pb_response = res.device_id.iden
    return res

Or you can get the device_id record from values as below:

@api.model
def create(self, values):
    if 'device_id' in values and values.get('device_id',False):
        device = self.env['device'].browse(values.get('device_id'))
        if device:
            values['pb_response'] = device.iden
    return super().create(values)

If the pb_response field is the same of the iden field then you can create it as related field to device_id.iden and you will get the iden value automatically once the device-id assigned as below:

 pb_response = fields.Char(related="device_id.iden")
Waleed Mohsen
  • 965
  • 6
  • 8