I have model
with order
indices, for example - 1, 2, 3, 5, 8, 10... (empty indices were allegedly removed - 4, 6, 7, 9...)
I need to get the index and swap it with the nearest index next to it. (for Up and Down move).
What I have:
def set_order_index(item: Posts, distinction: int):
items_to_swap = Posts.objects.filter(
order_index=item.order_index distinction)
if len(items_to_swap) > 0:
item_to_swap = items_to_swap[0]
item_to_swap.order_index = item.order_index
item_to_swap.save()
item.order_index = distinction
item.save()
And for Up
views ' 1':
def up_item(request, id):
item = Posts.objects.get(id=id)
set_order_index(item, 1)
return redirect('index')
And for Down
'-1'...
But my set_order_index
only does 1 and -1 always, and if it gets the same value, then swaps places. That is if index 3, the set_order_index
will only make 4 ( 1), but I need to swap 3 with 5. Because there is no index 4.
And if I use Post
with index 10 to Down
- I need to swap with 8, but my set_order_index
only do -1, and I get only 9. But I need 10 to swap with 8 immediately.
In my head, I understand how to do this through QuerySet, getting the indices of all that is > and < and then select the first or last - it is necessary, the neighbor. But in the code, I can't do it for it to work.
CodePudding user response:
def swap_up(item):
nextItem = Posts.objects.filter(order_index__gt=item.order_index).order_by('order_index').first()
if nextItem:
item_index = item.order_index
item.order_index = nextItem.order_index
nextItem.order_index = item_index
item.save()
nextItem.save()
def swap_down(item):
prevItem = Posts.objects.filter(order_index__lt=item.order_index).order_by('order_index').last()
if prevItem:
item_index = item.order_index
item.order_index = prevItem.order_index
prevItem.order_index = item_index
item.save()
prevItem.save()