I want to achieve something relatively simple: I want to retrieve all objects from my model given a range of ids (for eg, retrieve the lines 5 to 10 from a book's chapter).
Right now in my views.py, I've:
def line_range(request, book_id, chapter_id, line_start, line_end):
book_name = get_object_or_404(Book, id = book_id)
chapter_lines = []
for i in range (int(line_start), int(line_end)+1):
chapter_lines .append(Line.objects.get(book = book_id, chapter = chapter_id, line = i))
return render_to_response('app/book.html', {'bookTitle': book_name, 'lines': chapter_lines })
Now, this is obviously not the most optimized way of doing things, as it would do n database queries, when it could be done in only one. Is there a way of doing something like:
def line_range(request, book_id, chapter_id, line_start, line_end):
book_name = get_object_or_404(Book, id = book_id)
lines_range = range (int(line_start), int(line_end)+1)
chapter_lines = get_list_or_404(Line, book = book_id, chapter = chapter_id, line = lines_range)
return render_to_response('app/book.html', {'bookTitle': book_name, 'lines': chapter_lines })
This would in theory generate a much better database query (1 instead of n) and should be better performance wise. Of course, this syntax does not work (expecting an integer, not a list).
Thanks!