我正在用外键过滤模型的对象。结果是30.000条记录,而我的共享主机服务器出现内存错误。
如何编写部分查询(例如,查询限制为1000个结果)?
您认为在模板中使用StreamingHttpResponse有帮助吗?
发布于 2014-08-14 23:25:20
使用Python的数组拼接表示法,可以很容易地在Django中限制查询。您可以在任何查询中使用此方法。下面是一些示例:
# Will return only the first 1000 objects in the query
queryset = MyModel.objects.filter(some_field=some_value)[:1000]
# Will return only the first 500 objects
queryset = MyModel.objects.all()[:500]
# Will return the first 1000 objects of the filtered query ordered by the objects pk
queryset = MyModel.objects.filter(some_field=some_value).order_by('pk')[:1000]
# Will return the 25th through 50th object
queryset = MyModel.objects.all()[25:50]
# Will return all objects but the first 10
queryset = MyModel.objects.all()[10:] Django在这一点上很聪明,它只会查询所需的内容,然后停止,而不是收集整个查询,然后将其余的查询删除。
有关更多细节,请参见这里的文件。
发布于 2021-02-06 12:49:18
您可以使用以下方法。它将遍历按主键排序的Django Queryset。
def queryset_iterator(queryset, chunksize=1000):
pk = 0
last_pk = queryset.order_by("-pk")[0].pk
queryset = queryset.order_by("pk")
while pk < last_pk:
for row in queryset.filter(pk__gt=pk)[:chunksize]:
pk = row.pk
yield row
gc.collect()https://stackoverflow.com/questions/25318019
复制相似问题