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

Hi, I've created a custom module in which I added these three models named "dipendenti.py" (just consider it such as "students" to simplify things), "corso.py" and "edizione.py" (in Italian, "corso" is a word used to refer to a course in general, such as it would be literature, and "edizione" is a word used to refer to a specific course that has been holded, such as it would be literature in XX-HighSchool in 9th grade in the 2020-21 academic year). I'll write down the important code lines to contextualize:


DIPENDENTE.PY
class Dipendente(models.Model):
_name="piani_formazione.dipendente"
[...]codice_fiscale = fields.Char(string="Codice Fiscale", size=16, required=True)
dipendente_edizioni = fields.Many2many("piani_formazione.edizione","tabella_dipendenti_edizioni","codice_fiscale","numero",string="Edizioni frequentate")
CORSO.PY
class Corso(models.Model):
_name ="piani_formazione.corso"
[...]codice = fields.Char(string="Codice", required=True)
edizioni_corso = fields.One2many("piani_formazione.edizione","edizione_corso", string="Edizioni erogate")
EDIZIONE.PY
class EdizioneCorso(models.Model):
_name="piani_formazione.edizione"
[...]numero=fields.Text(string="Numero",required=True)
edizione_corso = fields.Many2one("piani_formazione.corso",string="Edizione del corso",required=True)
edizione_dipendenti = fields.Many2many("piani_formazione.dipendente","tabella_dipendenti_edizioni","numero","codice_fiscale",string="Frequentanti")

Now I would like to add to the "edizione.py" a computed field, that for each record ("for each edizione") registers how many dipendenti ("students") have attended that edizione ("specific course"). But I don't know how to count such quantity from tables, since the Many2many relation generates tables  instead of lists. 

Avatar
Discard
Author

@samuel I tried, but, since the relation creates a table and not a list, "len()" seems to not work on it

Author Best Answer

@samuel I found out that len() was not the problem, I just indented wrong the method! Thank you :)

Avatar
Discard

You're welcome

Best Answer

Hello Raib,

Try this:

Let's assume that you created your computed field like this:

dipendenti_number = fields.Integer(compute='_compute_dipendenti_number')

Now in your compute function

@api.depends('edizione_dipendenti')
def _compute_dipendenti_number(self):
    for rec in self:
        rec.dipendenti_number = len(rec.edizione_dipendenti)



Avatar
Discard
Related Posts Replies Views Activity
3
Apr 24
997
0
May 24
46
1
Apr 24
1822
2
Dec 23
920
1
Feb 24
924