从数据库加载大数据并转换为 JSON 时如何提高性能

Sim*_*ang 5 python django json django-models python-2.7

我编写了一个处理财务数据处理的 Djano 应用程序。我必须从 MySQL 表加载大数据(超过 1000000 条记录),并将记录转换为 django 视图中的 JSON 数据,如下所示:

trades = MtgoxTrade.objects.all()
data = []
for trade in trades:
            js = dict()
            js['time']= trade.time
            js['price']= trade.price
            js['amount']= trade.amount
            js['type']= trade.type
            data.append(js)
return data
Run Code Online (Sandbox Code Playgroud)

问题是FOR循环非常慢(200000条记录需要9秒以上),有没有有效的方法在Python中将DB记录转换为JSON格式数据?

更新:我已经根据 Mike Housky 在我的 ENV(ActivePython2.7,Win7) 中的答案运行代码,代码更改和结果为

def create_data(n):
    from api.models import MtgoxTrade
    result = MtgoxTrade.objects.all()

    return result


  Build ............ 0.330999851227
  For loop ......... 7.98400020599
  List Comp. ....... 0.457000017166
  Ratio ............ 0.0572394796312
  For loop 2 ....... 0.381999969482
  Ratio ............ 0.047845686326
Run Code Online (Sandbox Code Playgroud)

你会发现for循环大约需要8秒!如果我注释掉 For 循环,那么 List Comp 也需要这样的时间:

Times:
  Build ............ 0.343000173569
  List Comp. ....... 7.57099986076
  For loop 2 ....... 0.375999927521
Run Code Online (Sandbox Code Playgroud)

我的新问题是for循环是否会接触数据库?但我没有看到任何数据库访问日志。这么奇怪!

Sim*_*ser 2

您可以使用列表理解,因为它可以防止许多dict()andappend()调用:

trades = MtgoxTrade.objects.all()
data = [{'time': trade.time, 'price': trade.price, 'amount': trade.amount, 'type': trade.type}
        for trade in trades]
return data
Run Code Online (Sandbox Code Playgroud)

函数调用在 Python 中是昂贵的,因此您应该在慢循环中避免它们。