我需要使用 django reset_queries()

yos*_*ssi 5 python django orm memory-leaks django-models

我正在使用 django 1.3,并且正在 Web 上下文之外运行脚本(从命令行)。
我的代码每次都会从数据库读取 10000 个条目。
我注意到随着时间的推移,该进程的内存使用量越来越大。
我的代码是:

def getData(startIndex,chunkSize):
    dataList =Mydata.objects.filter(update_date__isnull = True)[startIndex:startIndex+chunkSize]
    return list(dataList)

if __name__ == '__main__':
   chunkSize = 10000
   startIndex = 0
   dataSize = Mydata.objects.filter(update_date__isnull = True).count()
   while startIndex < dataSize:
       dataList = getData(startIndex,chunkSize)
       startIndex += chunkSize
       do_stuff(dataList)
Run Code Online (Sandbox Code Playgroud)

我的问题是:我是否需要使用reset_queries()and connection.close()
or ,这是内存使用量增加的原因吗?

Mar*_*mro 2

我将从在查询中使用或延迟方法开始。这两个用于仅检索您实际需要的字段,而不是所有字段。您的查询会稍微快一些并且消耗更少的内存,因为不会从数据库中获取不需要的字段。