0

I want make code can calculate age

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

but wrong 'cursor' object has no attribute 'browse', what the problem ?

P.S : This my new code

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'),
J.C
  • 75
  • 4
  • 12

4 Answers4

3

The error message is not related to the date calculation. You might be using a module incompatible with the version of OpenERP you are using.

You need to provide more details about your module, OpenERP and addons version, and full traceback.

While irrelevant to the error, your age calculation would yield a negative value.

A simpler code would be:

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

Regarding the new code and error message below, You cannot append to a list by assigning to new index, change result to be a dictionary instead; Change result = [] to result = {}

Mohammad Alhashash
  • 1,543
  • 1
  • 14
  • 30
  • 1
    You surely ment `/365` instead of `/356`. I'm not a fan of this division by days approach, but if you use it it's more accurate to divide `/365.25`. But IMHO it's best to count months and divide by 12. I a posted a function for this [here](http://stackoverflow.com/a/9033133/959570). – Daniel Reis Jul 23 '12 at 14:30
  • The 2nd version has incorrect call to browse(). You should call self.browse() as calling browse() should be undefined in the function context. – Mohammad Alhashash Jul 24 '12 at 02:50
  • already I tried. but same error. like this right `records = self.browse(cr, uid, ids, context=context) ` – J.C Jul 24 '12 at 04:01
  • @MohammadAli I want make, float..., so if we choose 27 - March -1989. in fields age the result "23" – J.C Jul 24 '12 at 08:01
  • please help me...this really2 urgent – J.C Jul 24 '12 at 08:07
1

Following is my code. it returns a string.

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',),
}
OmaL
  • 5,037
  • 3
  • 31
  • 48
0

I created the student module and get the age field from the date of birth field using compute field

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>
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'))
Nihal
  • 5,262
  • 7
  • 23
  • 41