Reputation: 499
I have a Django app where values in a table can be reordered by the user, and new values can be added and old values can be deleted.
What is the "right" way to do this?
I could define order = models.IntegerField()
And then set that for each row to the right value in order to create the correct custom ordering as defined by the user. BUT this has the major downside that every re-order will require every row after the change to be updated with a new order
. I could make the code a bit smarter and define the Integer chosen to be halfway between the previous and the next - but that still means that occasionally there will be a conflict and all rows will have to be updated.
One possible solution is to use a float. Then the order of an inserted row can always be halfway between the previous and next... Are there any possible issues with using a float for ordering (particularly if the number of rows gets very high).
Is there a better/smarter/more built-in way to handle something like this?
Upvotes: 2
Views: 616
Reputation: 111325
I'm interested to hear any more clever solutions but I doubt there is anything simpler than integer order field, that's what I've been using.
To avoid value conflicts you need to not let the users customize this value directly, do it automatically behind the scenes based on some sort of ordering GUI (drag and drop, etc).
The workflow would be something like: show a list to the user, let them rearrange it however they want, submit the whole list back in order and update ordering for every record, starting with 1 and going +1.
If you are expecting users only to swap a pair of items occasionally, or insert new items into the middle, then you can update the order using UPDATE queries without looping through the list manually (UPDATE table set orderid = orderid + 1 where orderid >= :position
to insert a new item at a certain position, etc).
You shouldn't have too many entries in that list to worry about DB update performance since users are expected to sort the items manually somehow, you can't give them a million records to sort. If it's the case then you probably need to do something extra so the number of items users are ordering is manageable.
Upvotes: 2