2017-08-23 12 views
0

生年月日フィールドを持つ人物モデルを作成する必要があります。私は生年月日から人の年齢を数えるロジックを入れていません。計算フィールドをモデル化する方法

ここで計算フィールド内で使用するためにpythonのdatetimeをインポートする必要がありますか? datetime関数を呼び出そうとすると、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 

答えて

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)) 
ための正しいコードである私のモデルである

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

私の見解であります

関連する問題