[英]Only process subset of a queryset in Django (and return original queryset)
I have a generic list view in Django which returns around 300 objects (unless a search is performed). 我在Django中有一个通用列表视图,它返回大约300个对象(除非执行搜索)。
I have pagination set to only display 10 of the objects. 我将分页设置为仅显示10个对象。
So I query the database, then iterate through the objects, processing them and adding extra values before the display. 所以我查询数据库,然后遍历对象,处理它们并在显示之前添加额外的值。 I noticed that all 300 objects get the processing done, and the pagination is done after the processing. 我注意到所有300个对象都完成了处理,并且在处理之后完成了分页。 So I want to only do the processing on the objects that are going to displayed to increase performance. 所以我想只对要显示的对象进行处理以提高性能。
I calculate the indexes of the objects in the queryset that should be processed 0-10 for page 1, 11-20 for page 2, 21-30 for page 3, etc. 我计算了查询集中对象的索引,第1页应该处理0-10,第2页需要11-20,第3页需要21-30。
Now I want to process only the objects in the display range but return the full queryset (so the genreic view works as expected). 现在我想只处理显示范围内的对象,但返回完整的查询集(因此genreic视图按预期工作)。
Initially I tried: 最初我尝试过:
for object in queryset[slice_start:slice_end] :
# process things here
return queryset
But the slicing seems to return a new queryset, and the original queryset objects do not have any of the calculated values. 但切片似乎返回一个新的查询集,并且原始查询集对象没有任何计算值。
Currently my solution is: 目前我的解决方案是:
index = -1
for object in queryset:
index += 1
if index < slice_start or index > slice_end : continue
# process things here
return queryset
Now this works, but it seems rather hacky, and unelegant for Python. 现在这个工作,但它似乎相当hacky,并且对于Python来说不够优雅。 Is there a more pythonic way to do this? 是否有更多的pythonic方式来做到这一点?
If you're using Django's Paginator
class ( docs ), then you can request the current page and iterate over those objects in the view: 如果您正在使用Django的Paginator
类( docs ),那么您可以请求当前页面并在视图中迭代这些对象:
from django.core.paginator import Paginator
# in the view:
p = Paginator(objects, 2)
page = p.page(current_page)
for o in page.object_list:
# do processing
pass
You can obtain the value for current_page
from the request's parameters (eg, a page
parameter in request.GET
). 您可以从请求的参数中获取current_page
的值(例如, request.GET
的page
参数)。
您应该对page.object_list
的结果进行处理,该结果将保证仅包含该页面的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.