我想实现一些相对简单的东西: 我想在给定一系列 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)并且应该在性能方面更好。 当然,这种语法不起作用(需要一个整数,而不是一个列表)。
谢谢!
最佳答案
我想你想要__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.
我想你的应该是:
chapter_lines = get_list_or_404(..., line__range=(int(line_start), int(line_end)+1))
同样,您可以使用 __lt
, __gt
, __lte
, __gte
用于单方面比较。
我鼓励您始终打开 Django 文档窗口。如果您只是看看,那里有很多很棒的信息。
https://stackoverflow.com/questions/11229212/