Odoo Help

Welcome!

This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.

1

How to get a value of field in SQL query on a onchange function?

By
Remya
on 5/31/14, 2:15 AM 3,454 views

i have an on_change function in my education erp. Code is below:

def onchange_for_month(self, cr, uid, ids, months, context=None):
        '''This method automatically change value of month 
        @param self : Object Pointer
        @param cr : Database Cursor
        @param uid : Current Logged in User
        @param ids : Current Records
        @point : Apply method on this Field name
        @param context : standard Dictionary
        @return : Dictionary having identifier of the record as key and the value of month
        '''
        
        if not months:
            return {}
        tr_start_date = time.strftime("%Y-%m-%d")
        tr_end_date = datetime.strptime(tr_start_date, '%Y-%m-%d') + relativedelta(months= +months)
        date = datetime.strftime(tr_end_date, '%Y-%m-%d')
        return {'value': {'reg_end_date': date}} 

 

i have rewrite the code to 

 

def onchange_for_month(self, cr, uid, ids, months, context=None):
        '''This method automatically change value of month 
        @param self : Object Pointer
        @param cr : Database Cursor
        @param uid : Current Logged in User
        @param ids : Current Records
        @point : Apply method on this Field name
        @param context : standard Dictionary
        @return : Dictionary having identifier of the record as key and the value of month
        '''
        
        if not months:
            return {}
        tr_start_date = time.strftime("%Y-%m-%d")
        tr_end_date = datetime.strptime(tr_start_date, '%Y-%m-%d') + relativedelta(months= +months)         
        part_name = context.get('part_name') 
        cr.execute('select count(1) from transport_registration where reg_date = %s and reg_end_date <= %s ', (tr_start_date,tr_end_date))
        res = cr.fetchone()
        if res[0]==0:
           date = datetime.strftime(tr_end_date, '%Y-%m-%d')
           return {'value': {'reg_end_date': date}}                
        else:
           raise osv.except_osv(_('Error!'), _('Already this period is existing for the student')) 
           return {}

this function is working. And i got the alert

 

The onchange function is calling from the below code.

def create(self, cr, uid, vals, context=None):
        ''' This method create transport registration
        @param self : Object Pointer
        @param cr : Database Cursor
        @param uid : Current Logged in User
        @param vals : dict of new values to be set
        @param context : standard Dictionary
        @return :ID of newly created record.
        '''
        
        ret_val = super(transport_registration, self).create(cr, uid, vals, context=context)
        m_amt = self.onchange_point_id(cr, uid, ret_val, vals['point_id'])
        ex_dt = self.onchange_for_month(cr, uid, ret_val, vals['for_month'])        
        res = {}
        m_amount = m_amt.get('value', {}).get('m_amount', 0)
        reg_end_date = ex_dt.get('value').get('reg_end_date', False)
        if m_amount:
           res.update({'m_amount': m_amount})
        if reg_end_date:
           res.update({'reg_end_date': reg_end_date})
        self.write(cr, uid, ret_val, res, context=context)
        return ret_val
   ( table contains the below values)

class transport_registration(osv.osv):
    
    _name = 'transport.registration'
    _description = 'Transport Registration'
    _columns = {
        'name': fields.many2one('student.transport', 'Transport Root Name', domain=[('state', '=', 'open')], required=True),
        'part_name': fields.many2one('student.student', 'Participant Name', required=True),
        'reg_date': fields.date('Registration Date', readonly=True),
        'reg_end_date': fields.date('Registration End Date', readonly=True),
        'for_month': fields.integer('Registration For Months'),
        'state':fields.selection([('draft', 'Draft'),
                                      ('confirm', 'Confirm'),
                                      ('cancel', 'Cancel')
                                     ], 'State', readonly=True),
        'vehicle_id': fields.many2one('transport.vehicle', 'Vehicle No', required=True),
        'point_id': fields.many2one('transport.point', 'Point', widget='selection', required=True),
        'm_amount': fields.float('Monthly Amount', readonly=True),
        'amount': fields.float('Final Amount', readonly=True),
    }
    _defaults = {
        'state':'draft',
        "reg_date": lambda * a: time.strftime("%Y-%m-%d %H:%M:%S")
    }

 

I doubt is how can i get current part_name value in the onchange_for_month(like they pass month value). to change the sql query into

 

cr.execute('select count(1) from transport_registration where part_name = %s and reg_end_date <= %s ', (part_name,tr_start_date))

0
Mind And Go
On 6/1/14, 3:16 AM

Hy

Did you try to split the onchange function.
Onchange is a specific signature that is public and could be called from outside and moreover it could returns a message.
If you want to use the query, create a private function that will be called both from your create and onchange method.

EDIT : Try something like this (Take care of the copy paste):

def _onchange_for_month(self, cr, uid, ids, months, context=None):
       #Take care to raise no openep specific exception in this method
       if not months:
            return {}
        tr_start_date = time.strftime("%Y-%m-%d")
        tr_end_date = datetime.strptime(tr_start_date, '%Y-%m-%d') + relativedelta(months= +months)         
        part_name = context.get('part_name') 
        cr.execute('select count(1) from transport_registration where reg_date = %s and reg_end_date <= %s ', (tr_start_date,tr_end_date))
        res = cr.fetchone()
def onchange_for_month(self, cr, uid, ids, months, context=None):
   .../...
   my_res = self._onchange_for_month(cr, dui, ids, months, context)
   Make additionnal tests here and raise the excpetion here
 .../...
def create(self, cr, uid, vals, context=None):
   .../...
   my_res = self._onchange_for_month(cr, dui, ids, months, context)
   Make addtionnal tests here

 

Hi, Thanks for the reply. I didnt know how to split the onchange function. I am trying to get values in the same onchange function. I didnt get your answer. Please, can you explain it. Or can you update my python code.

Remya
on 6/2/14, 12:46 AM

I only want part_name in the onchange function. Did i get part_name = context.get('part_name') using this code? But i tried this code. Shows error. Any way i will try your code. But if any easy solution to get part_name in the onchange function month? Please update it.

Remya
on 6/3/14, 12:34 AM

If you want to get the part_name in the on_change method, you MUST pass the partner_id form the xml view. Don't forget the onchange method is not a javascript one, the UI will call the server method passing parameters. Add partner_id in the signature of your method and this will make context.get('partner_id') work! Regarsd

Mind & Go, Mind And Go
on 6/6/14, 4:35 AM

Your Answer

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!

About This Community

This community is for professionals and enthusiasts of our products and services. Read Guidelines

Question tools

1 follower(s)

Stats

Asked: 5/31/14, 2:15 AM
Seen: 3454 times
Last updated: 3/16/15, 8:10 AM