Django: How to Create Orderly Siblings

I want to create a model that will organize my children's models accordingly. For example, a book has many chapters, but the chapters must be in a certain order.

I assume that I need to put IntegerField in a chapter model that defines the order of the chapters, for example the following question: Ordered lists in django

My main problem is that whenever I want to insert a new chapter between two existing chapters or to reorder them in any way, I need to update (almost) every chapter in the book. Is there a way (possibly in Django Admin that I use) to avoid having to manually change each index in each chapter whenever I change the order?

I am not a big fan of creating a Linked List style model, as suggested in the above question, because I have the impression that it is not a good practice to create a database.

What is the “right” way to model this relationship?

+3
source share
2 answers

The answer you were talking about was probably the best way to deal with this effectively. Perhaps the original SQL statement is required UPDATE Chapter SET order = order + 1 WHERE book_id = <id_for_book> AND order <= <insert_index_location>. For Django 1.1 + : you can use F()to write on a single line, as shown below, but it can be O (n) requests 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)
+2
source

float , .

, 42 43, (42,5), - .

z x y... z.order = (y.order - x.order)/2 + x.order

+2

All Articles