我正在尝试在给定主键之前和之后选择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查询集技术
答案 0 :(得分: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]