在openerp中计算年龄

时间:2012-07-23 08:43:42

标签: openerp

我想make代码可以计算年龄

def _compute_age(self, cr, uid, ids, field_name, field_value, context=None):
    records = self.browse(cr, uid, ids, context=context)
    result={}
    for r in records:
        age=0
        if r.date_birth:
            d = strptime(r.date_birth,"%Y-%m-%d")
            count = date(d[0],d[1],d[2])-date.today()
            age = count.days/365 
        result[r.id] = age
    return result

但错误'游标'对象没有属性'浏览',有什么问题?

P.S: 这是我的新代码

def _compute_age(self, cr, uid, ids,field_name,field_value,arg, context=None):
    records = self.browse(cr, uid, ids, context=context)
    result = {}
    for r in self.browse(cr, uid, ids, context=context):
        age=0
        if r.date_birth:
            print date_birth
            age = (datetime.now()-datetime.strptime(r.date_birth,"%Y-%m-%d")).days/365.25
        result[r.id] = age 

    return result
_columns = {
    'date_birth': fields.date('Date of Birth'),
    'age' : fields.function(_compute_age, type='char', method=True, string='Age'),

4 个答案:

答案 0 :(得分:3)

错误消息与日期计算无关。您可能正在使用与您正在使用的OpenERP版本不兼容的模块。

您需要提供有关模块,OpenERP和插件版本以及完整追溯的更多详细信息。

虽然与错误无关,但您的年龄计算会产生负值。

更简单的代码是:

from datetime import datetime
...
    if r.date_birth:
        age = (datetime.now()-datetime.strptime(r.date_birth,"%Y-%m-%d")).days/356

关于下面的新代码和错误消息,您无法通过分配到新索引来附加到列表,而是将result更改为字典;将result = []更改为result = {}

答案 1 :(得分:1)

以下是我的代码。它返回一个字符串。

from dateutil.relativedelta import relativedelta
from datetime import datetime
def _compute_age(self, cr, uid, ids, field_name, arg, context={}):
    result = {}
    now = datetime.now()
    for r in self.browse(cr, uid, ids, context=context):
      if r.date_birth:
        dob = datetime.strptime(r.date_birth,'%Y-%m-%d')
        delta=relativedelta (now, dob)
        result[r.id] = str(delta.years) +"y "+ str(delta.months) +"m "+ str(delta.days)+"d" #if you only want date just give delta.years
      else:
        result[r.id] = "No DoB !"
    return result


_columns = {
    'age' : fields.function(_compute_age, method=True, type='char', size=32, string='Age',),
}

答案 2 :(得分:0)

我创建了学生模块,并使用计算字段

从出生日期字段中获取年龄字段

models.py

from openerp import models, fields, api
from dateutil.relativedelta import relativedelta
from datetime import date

class studentimg(models.Model):

     _name = 'studentimg.studentimg'
     name=fields.Char('Student')
     email = fields.Char('Email')
     phone = fields.Char('Phone')
     gender = fields.Selection([('m','Male'),('f','Female')],'Gender')
     is_active =fields.Boolean('Active')
     birth_date=fields.Date('Birth Date')
     age=fields.Char('Age',compute='calculate_age')
     image=fields.Binary()
     mat=fields.Integer('Maths')
     phy=fields.Integer('Physics')
     tot=fields.Integer('Total',compute='_computediff')

     @api.onchange('phy')
     def _computediff(self):
          self.tot = self.mat + self.phy

     def calculate_age(self):
         today = date.today()
         #self.age= today.year -  self.birth_date.year - ((today.month, today.day) < (self.birth_date.month, self.birth_date.day))
         yr=int(self.birth_date[0:4])
         mt=int(self.birth_date[5:7])
         dt=int( self.birth_date[8:10])
         self.age = today.year - yr - ((today.month, today.day) < (mt, dt))

templates.xml

<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id='student_form_view' model="ir.ui.view">
    <field name="name">Student Form View</field>
        <field name="model">studentimg.studentimg</field>
        <field name="arch" type="xml">
            <form string="Student Information">
                <sheet>
                        <field name="image" widget="image" class="oe_left oe_avatar"/>
                    <h2>
                        <field name="name"/>
                    </h2>
                           <notebook>
                             <page string="Public Information">
                                 <group>
                                          <group string="Contact Information" class="oe_left oe_avatar">
                                           <field name="email"/>
                                           <field name="phone"/>
                                          </group>



                                          <group string="Student Details">
                                             <field name="gender"/>
                                             <field name="is_active"/>
                                          </group>
                                          <group string="DOB">
                                              <field name="birth_date"/>
                                              <field name="age"/>
                                          </group>
                                          <group string="Total Marks">
                                              <field name="mat"/>
                                              <field name="phy"/>
                                              <field name="tot"/>
                                          </group>
                                 </group>
                             </page>
                           </notebook>
                </sheet>
            </form>
        </field>
</record>

<record id='student_tree_view' model="ir.ui.view">
    <field name="name">Student Tree View</field>
        <field name="model">studentimg.studentimg</field>
        <field name="arch" type="xml">
            <tree string="Student Details">
                <field name="image"/>
                <field name="name"/>
                <field name="email"/>
                <field name="phone"/>
                <field name="gender"/>
                <field name="is_active"/>
                <field name="birth_date"/>
            </tree>
        </field>
</record>
<record id="students_students_action" model="ir.actions.act_window">
       <field name="name">Students</field>
       <field name="res_model">studentimg.studentimg</field>
       <field name="view_mode">tree,form</field>
</record>

答案 3 :(得分:0)

birth_date = fields.Date('Birth Date')
age = fields.Char('Age',compute='_cal_age')

 @api.multi
    @api.depends('birth_date')
    def _cal_age(self):
        today = date.today()
        for record in self:
            age = []
            dob = fields.Date.from_string(record.birth_date)
            gap = relativedelta(today, dob)
            if gap.years > 0:
                record.age = str(gap.years) + ' Years'
            else:
                raise UserError(_('Birth Date must be Low than the Current Date'))