如何建模计算字段

时间:2017-08-23 08:03:35

标签: python openerp odoo-8

我需要创建具有出生日期字段的人员模型。我没有把逻辑从出生日算起来计算人的年龄。

我在哪里导入python的datetime以便在计算字段中使用?如果我尝试调用<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> 函数,Odoo会给我一个未定义的错误。

这是我的观点

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

这是我的模特

SELECT DISTINCT
    ex.*
FROM
    expert AS ex
    LEFT JOIN expert_competence AS ec ON ec.expert_id = ex.id
WHERE 
    FIND_IN_SET(ec.competence.id,'1,8') 

1 个答案:

答案 0 :(得分:1)

以下是从出生日期计算年龄的正确代码

    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))