Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
3 Trả lời
7352 Lượt xem

Hi all!

I have a model with a field that I want to constantly change.


This my model:

class TestModel(models.Model):
_name = 'test'

device = fields.Char(string="Device")

time = fields.Char()
lastTime = fields.Char()

In the controller I get the record id and the new lastTime value:

 def edit(self, **rec):
try:
        alert_last_time = request.env['test'].search([], limit=1)
alert_last_time.lastTime = rec['lastTime']
alert_last_time.write({'lastTime': rec['lastTime']})
except KeyError:
return {'success': False,
'message': 'KeyError'}
else:
return {'success': True,
'message': 'Record was successfully updated'}

If I create several records and try to change them, the first created record changes, but how to make the record whose id I have specified change, I do not yet understand


Ảnh đại diện
Huỷ bỏ
Bonjour, Je serai de retour le 2 septembre. Bien cordialement
Câu trả lời hay nhất

Hii,

Update your edit() method like this:
@http.route('/your/route', type='json', auth='public')  # adjust route details

def edit(self, **rec):

    try:

        record_id = int(rec['id'])  # make sure 'id' is passed in JSON body

        new_last_time = rec['lastTime']


        alert_last_time = request.env['test'].browse(record_id)


        if not alert_last_time.exists():

            return {'success': False, 'message': 'Record not found'}


        alert_last_time.write({'lastTime': new_last_time})

       

    except KeyError:

        return {'success': False, 'message': 'Missing "id" or "lastTime"'}

    except Exception as e:

        return {'success': False, 'message': str(e)}

    else:

        return {'success': True, 'message': 'Record was successfully updated'}


JSON Payload Example

Make sure your frontend or API call sends this:

{ "id": 3, "lastTime": "2025-07-16 17:00:00" }

i hope it is usefull

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

Hi,


In your program you are using the search method on your "test" module and limiting it by 1


python

alert_last_time = request.env['test'].search([ ], limit = 1)


if you want your program to work on a specific id, instead of using the "search" method use the "browse" method.


python

alert_last_time = request.env['test'].browse(your_id or ids)

your_id or ids" can be a single variable id or a list of ids


Hope it helps

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất
tobj = self.env['test'].search([ ], limit = 1) 
tobj.write({'lastTime': self.lastTime})


Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
2
thg 6 24
2678
1
thg 4 24
1745
1
thg 5 23
3636
5
thg 2 24
18016
2
thg 1 24
1573