以下代码BETWEEN
为 Django QuerySet 实现了 Erwin 的上述答案(使用 ):
将为任意 Django QuerySet 执行此操作的实用程序函数如下。它默认假设 'id' 是用于该between
子句的合适字段。
def chunked_queryset(qs, batch_size, index='id'):
"""
Yields a queryset split into batches of maximum size 'batch_size'.
Any ordering on the queryset is discarded.
"""
qs = qs.order_by() # clear ordering
min_max = qs.aggregate(min=models.Min(index), max=models.Max(index))
min_id, max_id = min_max['min'], min_max['max']
for i in range(min_id, max_id + 1, batch_size):
filter_args = {'{0}__range'.format(index): (i, i + batch_size - 1)}
yield qs.filter(**filter_args)
它将像这样使用:
for chunk in chunked_queryset(SomeModel.objects.all(), 20):
# `chunk` is a queryset
for item in chunk:
# `item` is a SomeModel instance
pass
您还可以更改界面,以便不需要额外的嵌套循环,但可以这样做for item in chunked_queryset(qs)
:
def chunked_queryset(qs, batch_size, index='id'):
"""
Yields a queryset that will be evaluated in batches
"""
qs = qs.order_by() # clear ordering
min_max = qs.aggregate(min=models.Min(index), max=models.Max(index))
min_id, max_id = min_max['min'], min_max['max']
for i in range(min_id, max_id + 1, batch_size):
filter_args = {'{0}__range'.format(index): (i, i + batch_size - 1)}
for item in qs.filter(**filter_args):
yield item