Compact primary keys
If the primary key on a table is an integer, it can be desirable after a lot of adding and removing either during testing (as was my case) or otherwise, to tidy up the key space a little and see the primary keys run up as unbroken sequences from 1. An excellent snippet here: https://djangosnippets.org/snippets/2915/ showed us how change the primary key value from in a given table and in all tables that relate to it (have a foreign key pointing into it). We can exploit that to achieve this outcome with integrity. For any given table we just fetch the primary keys into a sorted list and then walk the list assigning key 1, 2, 3, 4 etc where needed (if it doesn't already have that key).Because our list is sorted we're always moving tuples down the ladder of available keys to next empty slot basically until we've compacted the whole list. And voila. Mission accomplished. Works in with database introspection, in part because the integrity of relations is a little obscured by the ORM which hides intermediary tables in ManyToMany relationships and such. At the database API level these concerns all disappear. Built and tested with Django 1.11 but the form only goes to 1.10 here. Not even sure it works on 1.10. Certainly the snippet I based it on didn't work in 1.11 and need some updating.
- primary-key
- compact