Ir al contenido
Menú
Se marcó esta pregunta
2 Respuestas
861 Vistas

I am new here and wondering what type of field to put in the form for employee's age, what dependices to put and how to compute it?

Avatar
Descartar
Mejor respuesta

Hi Frederick,

Welcome to the forum! In order to calculate age you'll need to work from a Date of Birth field. It's unclear to which model you'd like to add the field, but if you were trying to add it to hr.employee, which already has a Date of Birth field named "birthday", you would need the following:

  • Dependency on the field "birthday"
  • New field type of either Integer or Float (depending if you want decimals in your calculation)
  • A calculation method, such as the one below. I am assuming you are entering this into the UI, not writing a module. If you are writing a module, you'll need to manually define an actual compute function on the model with some similar code inside the function.
for record in self:
​record.age = (datetime.date.today() - record.birthday).days / 365

I'm not aware of any other models with a date of birth field in Odoo, so you may need to actually create that field first if, for example, you are hoping to calculate the age of contacts in general (not just employees).

Good luck!

Avatar
Descartar
Mejor respuesta

Hello Frederick Hartanto,


I hope you are doing well!

To compute the age field you can refer below code:


//Code is added in comment


I Hope this information proves helpful to you.


Thanks & Regards,

Email:   odoo@aktivsoftware.com           

Skype: kalpeshmaheshwari 

Avatar
Descartar

.py:

date_of_birth = fields.Date(string="Date of Birth")
age = fields.Integer(string="Age", compute="_compute_age")

@api.depends('date_of_birth')
def _compute_age(self):
for rec in self:
if rec.date_of_birth:
today = date.today()
birth_date = fields.Date.from_string(rec.date_of_birth)
rec.age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
else:
rec.age = 0