我有model
与order
索引,例如- 1,2,3,5,8,10…(据称空索引被删除- 4,6,7,9…)
我需要得到索引并与它旁边最近的索引交换。(上下移动).
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()
对于Up
视图'+1':
def up_item(request, id):
item = Posts.objects.get(id=id)
set_order_index(item, +1)
return redirect('index')
为Down
和' 1 '
……但是我的set_order_index
总是只做+1和-1,如果它得到相同的值,那么交换位置。也就是说,如果索引3,set_order_index
只会使4(+1),但我需要用5交换3。因为没有索引4.
如果我使用索引为10到Down
的Post
-我需要与8交换,但我的set_order_index
只做-1,我只得到9。但是我需要马上把10换成8。
在我的脑海中,我理解如何通过QuerySet做到这一点,获得所有的索引是>和& lt;然后选择第一个或最后一个邻居,这是必要的。但是在代码中,我不能让它工作。
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()