1
주어진 기본 키 전후에 2 행을 선택하려고합니다. 지금까지 내 솔루션이지만 비효율적 인 것처럼 보입니다. 이 방법을 최적화 할 수 있습니까?pk 앞뒤에 행을 선택하는이 쿼리를 최적화하십시오.
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]))
이 작동하지만, 어쩌면