[Answered ]-How to deal with virtual index in a database table in Django + PostgreSQL

1👍

To insert at 10th position all you need is a single sql query:

MyModel.objects.filter(priority__gte=10).update(priority=models.F('priority')+1)

Then you would need a similar one for deleting an element, and swapping two elements (or whatever your use case requires). It all should be doable in a similar manner with bulk update queries, no need to manually update entry by entry.

👤serg

1👍

First, you can very well index this column, just don’t enforce it to contains unique values. Such standard indexes can have nulls and duplicates… they are just used to locate the row(s) matching a criteria.

Second, updating each populated* row each time you insert/update a record should be looked at based on the expected update frequency. If each user is inserting several records each time they use the system and you have thousands of concurrent users, it might not be a good idea… whereas if you have a single user updating any number of rows once in a while, it is not so much an issue. On the same vein, you need to consider if other updates are occurring to the same rows or not. You don’t want to lock all rows too often if they are to be updated/locked for updating other fields.

*: to be accurate, you wouldn’t update all populated rows, but only the ones having a priority lower than the inserted one. (inserting a priority 999 would only decrease the priority of items with 999 and 1000)

👤JGH

Leave a comment