从Django中的一系列ID中检索匹配对象的列表 [英] Retrieve a list of matching objects from a range of ids in Django
问题描述
我想实现一些相对简单的事情:我想从给定一定范围的ID的模型中检索所有对象(例如,从一本书的章节中检索第5至10行).
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).
现在在我的views.py中,我已经:
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 })
现在,这显然不是最优化的处理方式,因为它只能对一个数据库执行n个数据库查询.有没有办法做类似的事情:
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 })
从理论上讲,这将生成更好的数据库查询(用1代替n),并且应该在性能上更好.当然,这种语法不起作用(期望一个整数,而不是一个列表).
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).
谢谢!
推荐答案
我认为您想要 __ range
:
I think you want __range
:
范围测试(含).
Range test (inclusive).
示例:
开始日期= datetime.date(2005,1,1)
end_date = datetime.date(2005,3,31)
Entry.objects.filter(pub_date__range =(开始日期,结束日期))
等效于SQL:
SELECT ...在'2005-01-01'和'2005-03-31'之间的发布日期;
您可以在SQL中可以使用BETWEEN的任何地方使用范围-用于日期,数字甚至字符.
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
进行单方面比较
Likewise, you can use __lt
, __gt
, __lte
, __gte
for one-sided comparisons.
我鼓励您始终使用Django文档打开一个窗口.只要看一下,那里就会有很多很棒的信息.
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.
这篇关于从Django中的一系列ID中检索匹配对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!