2011-07-06 4 views
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])) 

이 작동하지만, 어쩌면

답변

0

은/ID가 적은 당신보다 더 큰 행을 취득하고, 2 개 행으로 제한 장고의 검색어 세트의 고급 기술을 사용하여,보다 효율적으로 뭔가를 찾고 있어요 .

next_objs = Media.objects.filter(id__gt=image.id).order_by('id')[:2] 
prev_objs = Media.objects.filter(id__lt=image.id).order_by('-id')[:2] 
관련 문제