Reputation: 15
I have a student form, in which, when a student select his/her date of birth, his age will show in "Calculated Age" field.
Now, I want that instead of showing only digit in numbers, I want to show it as:
Hi, Srishti! Your age is 9.
Note that "Srishti" is a name given in name field.
Please help.
Regards
Adesh Paul
class StudentStudent(models.Model):
_name = 'student.student'
student_dob = fields.Date(string="Date of Birth")
age = fields.Integer(string='Age')
calc_age = fields.Char(string="Calculated Age", readonly=True)
@api.onchange('student_dob')
def _onchange_birth_date(self):
"""Updates age field when birth_date is changed"""
if self.student_dob:
d1 = datetime.strptime(str(self.student_dob), "%Y-%m-%d").date()
d2 = date.today()
self.calc_age = relativedelta(d2, d1).years
Upvotes: 1
Views: 131
Reputation: 26738
You can define age
and calc_age
as computed fields instead of using onchange
method to set their values.
You can use the same compute method since both fields depend on the same field student_dob
.
Example:
student_dob = fields.Date(string="Date of Birth")
age = fields.Integer(string='Age', compute="_compute_age")
calc_age = fields.Char(string="Calculated Age", compute="_compute_age")
@api.depends('student_dob')
def _compute_age(self):
for record in self:
if record.student_dob:
age = relativedelta(
fields.Date.today(),
record.student_dob,
).years
record.age = age
record.calc_age = 'Hi, {}! Your age is {}'.format(record.name, age)
Import relativedelta
from dateutil.relativedelta
.
Upvotes: 1