G
G
Gasoid2016-05-26 14:02:43
Django
Gasoid, 2016-05-26 14:02:43

How to improve this query in django?

it is necessary to receive the following and previous object in request, it is sorted by a text field?

id_list = list(Product.objects.values_list('id', flat=True).order_by('title'))
next_id = id_list[id_list.index(cur_obj.id)+1]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2016-05-26
@fox_12

As an option like this (I took my model as an example, simply changing the names for yours):

In [1]: Product.objects.values_list('id', flat=True).order_by('title')
Out[1]: [6, 7, 2, 15, 5, 4, 12, 14, 16, 1, 13, 10, 8, 11, 9, 3]

In [2]: my_pk = 12

In [3]: Product.objects.raw('SELECT * FROM product WHERE title<(SELECT title FROM product WHERE id=%s) ORDER BY title DESC LIMIT 1',[my_pk])[0].pk
Out[3]: 4

In [4]: Product.objects.raw('SELECT * FROM product WHERE title>(SELECT title FROM product WHERE id=%s) ORDER BY title ASC LIMIT 1',[my_pk])[0].pk
Out[4]: 14

E
Egor Stakhovsky, 2016-05-27
@ySky

id_list = list(Product.objects.values_list('id', flat=True).order_by('title'))
current_pos = id_list.index(cur_obj.id)
next_and_prev = list(Product.objects.all().order_by('title')[current_pos-1:current_pos+2])

Not a special optimization, from 3 requests to 2.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question