从Django中的一系列ID中检索匹配对象的列表

sro*_*uez 2 django django-models

我想要实现一个相对简单的东西:我想在给定ID范围的情况下从模型中检索所有对象(例如,从书的章节中检索第5至10行)。

现在在我的views.py中,我已经:

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 })
Run Code Online (Sandbox Code Playgroud)

现在,这显然不是最优化的处理方式,因为它只能在一个数据库中完成n次数据库查询。有没有办法做类似的事情:

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 })
Run Code Online (Sandbox Code Playgroud)

从理论上讲,这将生成更好的数据库查询(用1代替n),并且应该在性能上更好。当然,此语法不起作用(期望整数,而不是列表)。

谢谢!

Pao*_*ino 5

我想你要__range

范围测试(含)。

例:

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等效项:

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

您可以在SQL中可以在BETWEEN中使用的任何位置使用范围-用于日期,数字甚至字符。

我想您的应该是:

chapter_lines = get_list_or_404(..., line__range=(int(line_start), int(line_end)+1))
Run Code Online (Sandbox Code Playgroud)

同样,你可以使用__lt__gt__lte__gte为片面比较。

我鼓励您始终打开Django文档的窗口。如果您看看的话,那里有很多很棒的信息。