Retrieve a list of matching objects from a range of ids in Django

邮差的信 提交于 2020-11-29 09:53:36

问题


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!


回答1:


I think you want __range:

Range test (inclusive).

Example:

start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
Entry.objects.filter(pub_date__range=(start_date, end_date))

SQL equivalent:

SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';

You can use range anywhere you can use BETWEEN in SQL — for dates, numbers and even characters.

So yours would be, I think:

chapter_lines = get_list_or_404(..., line__range=(int(line_start), int(line_end)+1))

Likewise, you can use __lt, __gt, __lte, __gte for one-sided comparisons.

I would encourage you to always keep a window open with the Django documentation. There is lots of great info there if you just look.



来源:https://stackoverflow.com/questions/11229212/retrieve-a-list-of-matching-objects-from-a-range-of-ids-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!