0
votes

I have a requirement to create person model with date of birth field. I haven't put the logic to count person's age from date of birth.

Where do I have to import python's datetime for use inside the computed fields? If I try to call datetime functions Odoo gives me undefined error.

This is my view

<record model="ir.actions.act_window" id="person_list_action">
    <field name="name">Person</field>
    <field name="res_model">earth.person</field>
    <field name="view_type">form</field>
    <field name="view_mode">tree,form</field>
    <field name="help" type="html">
        <p class="oe_view_nocontent_create">Create the first person
        </p>
    </field>
</record>

<record model="ir.ui.view" id="person_tree_view">
    <field name="name">person.tree</field>
    <field name="model">earth.person</field>
    <field name="arch" type="xml">
        <tree string="Person Tree">
            <field name="first_name"/>
            <field name="last_name"/>
            <field name="date_of_birth"/>
            <field name="age"/>
        </tree>
    </field>
</record>

This is my model

class Person(models.Model):
    _name = 'earth.person'

    first_name = fields.Char(string="First Name", required=True)
    last_name = fields.Char(string="Last Name")
    date_of_birth = fields.Date()
    age = fields.Integer(compute='_compute_person_age')

    @api.depends('date_of_birth')
    def _compute_person_age(self):
        for record in self:
            record.age = 30
1

1 Answers

1
votes

Here is the correct code for calculate the age from the birthdate

    from datetime import datetime, date     
    class Person(models.Model):
   _name = 'earth.person'

   first_name = fields.Char(string="First Name", required=True)
   last_name = fields.Char(string="Last Name")
   date_of_birth = fields.Date()
   age = fields.Integer(compute='_compute_person_age')

   @api.depends('date_of_birth')
   def _compute_person_age(self):
    today = date.today() 
    for record in self:
      if record.date_of_birth:
          born = datetime.strptime(record.date_of_birth,"%Y-%m-%d") 
          record.age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))