TypeError:元组索引必须是整数,而不是str / django

时间:2017-09-04 07:24:52

标签: python mysql django cursor

我对此有错误:

cursor = connection.cursor()

cursor.execute("SELECT username as username, sum(ACCTSESSIONTIME) as total_acctsessiontime FROM RADUSAGE GROUP BY username LIMIT 0, 10")

usage_summary = cursor.fetchall()

for row in usage_summary:
    row['total_acctsessiontime'] = 0 if row['total_acctsessiontime'] is None else humanize_seconds(row['total_acctsessiontime'])
    row['total_acctinputoctets'] = 0 if row['total_acctinputoctets'] is None else naturalsize(row['total_acctinputoctets'])
    row['total_acctoutputoctets'] = 0 if row['total_acctoutputoctets'] is None else naturalsize(row['total_acctoutputoctets'])

return jsonify(cursor)

错误:

Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/loc_rad/admin_app/dashboard.py", line 57, in inquiry
row['total_acctsessiontime'] = 0 if row['total_acctsessiontime'] is None else humanize_seconds(row['total_acctsessiontime'])
TypeError: tuple indices must be integers, not str

这是我第一次使用游标连接。我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

cursor.fetchall()返回了元组。在你的情况下,这个元组将如此: (('username1', 100), ('username2', 200),)

使用这种方法row['total_acctsessiontime']你应该每次在循环中创建dict,或者这样做

items = {'username': 0, 'total_acctoutputoctets': 1}
for row in usage_summary:
    row[item['total_acctsessiontime']] = 0 if row[item['total_acctsessiontime']] is None else humanize_seconds(row[item['total_acctsessiontime']])

但简单的方法是:

for row in usage_summary:
    row[1] = 0 if row[1] is None else humanize_seconds(row[1])

<强> UPDATE1

acctsessiontime, acctoutputoctets, acctinputoctets == [], [], []
for row in usage_summary:
    acctsessiontime.append(0 if row[1] is None else humanize_seconds(row[1]))
    acctoutputoctets.append(0 if row[1] is None else humanize_seconds(row[1]))
    acctinputoctets.append(0 if row[1] is None else humanize_seconds(row[1]))
all_sum = sum(acctsessiontime) + sum(acctoutputoctets) + sum(acctinputoctets)