Я пытаюсь выбрать 2 строки до и после заданного первичного ключа. Это мое решение до сих пор, но кажется неэффективным. Есть ли способ оптимизировать это?
images = Media.objects.filter(owner=user_object) #select objects by a user
id_list = list(images.values_list('id', flat=True)) #get the primary keys for the objects
idx = id_list.index(image.id) #get the index of the image
#TODO check for index error
next_ids = id_list[idx+1:idx+3] #get ids of next 2 objects
prev_ids = id_list[idx-3:idx-1] #get ids of previous 2 objects
#using the IDs, get the objects
next_objs = Media.objects.filter(Q(pk=next_ids[0]) | Q(pk=next_ids[1]))
prev_objs = Media.objects.filter(Q(pk=prev_ids[0]) | Q(pk=prev_ids[1]))
Это работает, но я ищу что-то более эффективное, возможно, с использованием более продвинутых методов наборов запросов django