Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the previous data or the latest data by id in Odoo?

I created a billing system where I have a fields of meter_no, prev_reading, current_reading and consumed. In my onchange method, when I select a meter number, my prev_reading will be automatically filled with the value of the last saved current_reading by id of a meter_no. Here's my onchange method:

@api.multi
@api.onchange('meter_no')
def onchange_meter_no(self):
    ids = self.search([('meter_no','=',self.meter_no.id)])
    last_id = ids and max(ids)
    if self.meter_no:
        self.prev_reading = last_id.current_reading or None

But this always returns the second value, not the last data. Example, BILL-01 prev_reading = 0.0, current_reading = 10.0, and consumed = 10.0. In BILL-02, the data is correct as expected where, prev_reading = 10.0, then I entered current_reading = 20, then consumed = 10. Here in third billing, BILL-03 prev_reading is always 10, it's always the same until fourth and so on. What's wrong with this? I already used the max() to get the last id.

like image 217
stonix26 Avatar asked Nov 02 '16 03:11

stonix26


1 Answers

You could pass options to search function to get the last id like this:

record_ids = self.search([('meter_no','=',self.meter_no.id)], order='id desc', limit=1)
last_id = record_ids.id

...

like image 175
thangtn Avatar answered Dec 29 '22 21:12

thangtn