Answer the question
In order to leave comments, you need to log in
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
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
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])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question