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

這工作,但我正在尋找的東西更有效,也許使用Django的查詢集的更先進的技術

回答

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]