2

我想实现一些相对简单的事情:我想从我的模型中检索给定一系列 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 })

现在,这显然不是最优化的处理方式,因为它会执行 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 })

这在理论上会产生一个更好的数据库查询(1 而不是 n),并且在性能方面应该更好。当然,这种语法不起作用(期望一个整数,而不是一个列表)。

谢谢!

4

1 回答 1

10

我想你想要__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 的地方使用 range —— 用于日期、数字甚至字符。

所以你会是,我认为:

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

同样,您可以使用__lt, __gt, __lte,__gte进行片面比较。

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

于 2012-06-27T15:05:47.023 回答