Skip to Content
Меню
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
Це запитання позначене
2 Відповіді
6422 Переглядів

In my module I have an entity "Person" with two fields "date_of_birth" (Date)  and "age" (Integer). How can I get the age of a Person from the date of birth?

Аватар
Відмінити
Найкраща відповідь

Hi Ernesto:

Make "age" a computed field with the following settings: 

  • Readonly = True

  • Stored = False

  • Copied = False

  • Depends on: date_of_birth

The code for the computation would be

for record in self:
  if record.date_of_birth:
today = datetime.date.today() # Check if the date has passed this year if today.strftime("%m%d") >= record.date_of_birth.strftime("%m%d"):
record['age'] = today.year - record.date_of_birth.year
else: record['age'] = today.year - record.date_of_birth.year - 1
else:
record['age'] = 0


Аватар
Відмінити
Найкраща відповідь

Hi Ernesto:
You can do like this:


from dateutil.relativedelta import relativedelta

age = fields.Integer(string="Age", compute="_calculate_age")

   @api.depend('date_of_birth')
    def _calculate_age(self):

          if self.date_of_birth:

             d1 = self.date_of_birth

            d2 = datetime.date.today()

           self.age = relativedelta(d2, d1).years


Аватар
Відмінити
Related Posts Відповіді Переглядів Дія
1
вер. 18
4724
1
січ. 17
5423
0
бер. 25
1823
4
квіт. 24
174848
2
бер. 24
2253