Django datatable: order by the last entry

I have a datatable with 11 columns. The first column is ID (pk) and the table is ordered by this primary key.

order: [[1, 'desc']]

I want to order all of the entries in my table by the last one added to the first one, as it is now, BUT I don't want some ID's to be skipped if I delete one record.

I tried to order them by a column "Date", but this is not what I want. I tried to hide the column ID, but then I can't order by the last one added.

Example: Before deletion:

ID NAME
1 John
2 Smith
3 Mark
4 Johnny

After deleting Smith (2) row:

ID NAME
1 John
3 Mark
4 Johnny

What I want:

ID NAME
1 John
2 Mark
3 Johnny

I am thinking about a new custom ID field but I want it to update everytime with the deletion of a middle record. Another way is to hide the column ID, but if I click to sort them by Name, I can't sort them back by ID only if I refresh the page. Do you have any solutions ? Thanks

Please don't. Primary keys should be seen as blackbox tokens that in this case "happen" to be integers, but that is a technical detail.

The database often uses primary keys to refer to the object, through FOREIGN KEYs. If you update a primary key, everything that has to refer to these primary keys must also be updated, which can have huge impact on the database. Still, even worse: not everything explicitly has a FOREIGN KEY constraint, making it thus impossible to guarantee that everything has been updated correctly.

Moreover, primary keys are typically used in the URLs to refer to these objects. This thus means that if you update the primary key, then a (bookmarked) URL will no longer point to Mark, but to Johnny after the update. As the w3 organization says: Cool URIs don't change [w3.org].

You can use a hidden column [datatables-doc], and sort with that hidden column. As said, a primary key should be seen as a technical detail, not some value to display or manipulate: sure the primary keys are for example integers, but adding two primary keys together makes no sense. So these are not "integers" with all the cool features of integers, these are integers to store the data efficiently.

Back to Top