2π
β
The answer you alluded to was probably the best way to handle this efficiently. Probably requiring a raw SQL statement UPDATE Chapter SET order = order + 1 WHERE book_id = <id_for_book> AND order <= <insert_index_location>
. For Django 1.1+: You could use F()
to write this in a single line as the following, but it might still be O(n) queries under the hood, using transactions.
Book.objects.get(id=<id_of_book>).chapter_set.filter(order__gt=<place_to_insert>).update(order=F('order')+1)
π€Furbeenator
2π
Use a float instead of an integer to avoid your problem of updating multiple items when you insert between two.
So if you want to insert an item between item 42 and item 43, you can give it an order value halfway between the two (42.5), and you wonβt have to update any other items.
Insert z between x and yβ¦
z.order = (y.order β x.order) / 2 + x.order
π€user391538
- [Django]-Django templates iterate through list of tuples and give them all buttons
- [Django]-Saving a model serializer with a nested relationship with Django Rest Framework
- [Django]-Django Oauth Toolkit 2-legged and 3-legged
- [Django]-TemplateDoesNotExist at / base/index.html
Source:stackexchange.com