[Django]-Django: How to create ordered siblings

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

Leave a comment