Skip to Content
Menu
This question has been flagged
2 Replies
2983 Views

Hi, I would like to save all the records of a model inside its python file as a string 'x,y,z..', inside a fields.Char or fields.Text. I thought about using a computational field (fields.Char(compute="...")) and the self.env().search([]) inside the method, but I can't really find a code that works. Can anyone help me defining this method/function (with eventual apis)?

The model that I want to save the records of is:

class Corso(models.Model):    
_name = 'piani_formazione.corso'
_rec_name = 'codice'
codice = fields.Char(string="Codice del corso", required=True, readonly=True) 

Avatar
Discard
Best Answer

please try the below code to get all records:

codice = fields.Char(string="Codice del corso", compute="_compute_model_field")

def _compute_model_field(self):
my_obj = self.env['piani_formazione.corso']
record_ids = self.search([])
model_records = ""
if record_ids:
for record in record_ids:
new_dict = record.read(list(set(my_obj._fields)))
model_records = model_records + str(new_dict) + ","
print(new_dict)
self.codice = model_records


Avatar
Discard
Author Best Answer

I tried, naming the field "elenco_codice" (=list of codes) instead of codice (=code), but it gave me back this string: 

[{'id': 1, 'descrizione': False, 'durata': 0, 'create_date': datetime.datetime(2021, 10, 4, 22, 34, 39, 967662), '__last_update': datetime.datetime(2021, 10, 8, 13, 53, 35, 170279), 'elenco_corsi': False, 'display_name': '001 - Sicurezza', 'costo_a_persona': 0.0, 'write_date': datetime.datetime(2021, 10, 8, 13, 53, 35, 170279), 'validità': 0, 'nome': 'Sicurezza', 'categoria_rischio': False, 'edizioni_corso': [1, 2], 'codice': '001', 'write_uid': (1, 'OdooBot'), 'create_uid': (1, 'OdooBot'), 'docenti_corso': [1, 2], 'currency_id': (1, 'EUR')}],[{'id': 2, 'descrizione': False, 'durata': 0, 'create_date': datetime.datetime(2021, 10, 4, 22, 34, 49, 514492), '__last_update': datetime.datetime(2021, 10, 15, 6, 48, 34, 855446), 'elenco_corsi': '[{\'id\': 1, \'descrizione\': False, \'durata... etc etc etc...

maybe I hadn't been specific enought: I would like to save all the valued of the field "codice" for every record in this string

---------------------------------

Thank you! I fixed the function and now it works! This is the final code that I used

def _compute_model_field(self):
  my_obj = self.env['piani_formazione.corso'].search([])
  model_records = ''
  if my_obj:
    for record in my_obj:
      model_records = model_records + str(record.codice) + ","
  self.elenco_corsi = model_records

Avatar
Discard