0

我想让代码可以计算年龄

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

但是错误的“光标”对象没有“浏览”属性,有什么问题?

PS:这是我的新代码

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

4 回答 4

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 = {}

于 2012-07-23T11:35:17.523 回答
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',),
}
于 2012-07-24T05:05:45.390 回答
0

我创建了学生模块并使用计算字段从出生日期字段中获取年龄字段

模型.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))

模板.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>
于 2017-09-15T04:36:43.157 回答
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'))
于 2018-08-13T07:25:10.960 回答