跳至内容
菜单
此问题已终结
2 回复
6210 查看

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


形象
丢弃
相关帖文 回复 查看 活动
1
9月 18
4577
1
1月 17
5233
0
3月 25
1590
4
4月 24
174489
2
3月 24
2085