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

I am trying to get the last record id with out using the create() from the ORM. Does anyone know how to get a last record id from a table? thank you

Ảnh đại diện
Huỷ bỏ

Maybe with SELECT max(id) FROM table

Tác giả Câu trả lời hay nhất

Well I finally got something working. This is what I did, I used the database cursor and wrote an sql select statement like this:

cr.execute('select "id" from "table_name" order by "id" desc limit 1')

id_returned = cr.fetchone()

the fetchone() method returns a tuple of one value which is assigned to the id_returned variable. I can then get the id from the tuple by referencing the first index like this: id_returned[0]

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

Not quite sure about the older versions but you can do it like this in the newer ones:

last_id = self.env['table.name'].search([])[-1].id
Ảnh đại diện
Huỷ bỏ

The ordering of the table might be such that the highest id is not equivalent to the last entry in the list. Thus I would explicitly provide the order in the search method:

last_id = self.env['table.name'].search([], order='id desc')[0].id

Câu trả lời hay nhất

If you don't want to execute PSQL query then you can search the record and get the max number, eg.

search_ids = self.pool.get("res.partner").search(cr, uid, [])
last_id = search_ids and max(search_ids)
Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

The sequencing is also stored in the database and can be retrieved with a statement like:

select * from res_partner_id_seq

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

you can use something like this :


max(model('helpdesk.ticket').search([]))

the solution like the above does not work. It returns the id of the last one in the search() method, but the ids are not sorted. The last id should not be the max one.

last_id = self.env['table.name'].search([])[-1].id
Ả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 16
3208
3
thg 1 16
4529
0
thg 6 24
1442
2
thg 8 23
2431
1
thg 10 22
6420