İçereği Atla
Menü
Bu soru işaretlendi
2 Cevaplar
22039 Görünümler

Hi,

I am new to Odoo. I have a requirement to create person model with date of birth. Can I use compute field for the person's age?

I haven't put the logic to count person's age from date of birth. Also I see that the physical table does not contain the compute field. 

But when I tried to view the module I created, the age does not display number 30.

How to use the compute field so that the user don't have to input the age (auto calculate from date of birth) and everytime I view the record, the age calculate according to current date?

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>

        <!-- override the automatically generated list view for courses -->
        <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):
  return 30

Avatar
Vazgeç
En İyi Yanıt

Hi Erwin,

You can try like this,

@api.depends('date_of_birth')
def _compute_person_age(self):
if self.date_of_birth:
birth_date = datetime.strptime(self.birth_date, '%m/%d/%Y')
self.age = (datetime.today() - birth_date).days / 365

Also you can check this link ,https://stackoverflow.com/questions/2217488/age-from-birthdate-in-python

Thanks

Avatar
Vazgeç
Üretici En İyi Yanıt

Hi Niyas thank you for the answer.

I tried your code it gives me global name datetime is not defined. Where should I import datetime to use inside compute fields?

Avatar
Vazgeç

Not inside the compute function, you have to import in the top of the python file

İlgili Gönderiler Cevaplar Görünümler Aktivite
1
Haz 25
16493
3
Nis 25
7091
Compute Fields Çözüldü
2
Tem 24
9059
1
Oca 24
2560
2
Ara 22
15515