在django中,我使用了连接概念来获取数据。输出有多个记录需要解析。
cursor = connections['configuration'].cursor()
cursor.execute("SELECT DISTINCT(integrations.trail_userid),integrations.environment, integrations.endpoint, integrations.connectivity_status, integrations.subscription_status from integrations INNER JOIN list_integration_tools ON integrations.endpoint = list_integration_tools.endpoint WHERE integrations.`trail_username`='ambika02'")
row = cursor.fetchall()
print(row)
这是我的密码 行的结果是((30,None,'snow','production','dev'),(30,None,'jira','production','production'))
我需要遍历行以获取所有值
row [0]给我第一条记录(30,无,“雪”,“生产”,“开发”),但是我如何解析第一条记录
答案 0 :(得分:1)
您甚至可以使用该属性将所有属性名称及其表的值取出到字典列表中,这也将有助于您在Django模板中进行解析,并且还将避免视图和模板中出现2个循环>
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
cursor = connections['configuration'].cursor()
cursor.execute("SELECT DISTINCT(integrations.trail_userid), integrations.environment,
integrations.endpoint, integrations.connectivity_status,
integrations.subscription_status
FROM integrations INNER JOIN list_integration_tools
ON integrations.endpoint = list_integration_tools.endpoint
WHERE integrations.`trail_username`='ambika02'")
all_data = dictfetchall(cursor)
答案 1 :(得分:0)
您可以使用for循环并遍历行。每行都是元组,因此您可以按其索引访问值。
请参见以下示例:
for subrow in row:
subrow[0]
subrow[1]
subrow[2]
subrow[3]
subrow[4]
如果要访问第一条记录,请尝试:
row[0][0]
row[0][1]
row[0][2]
row[0][3]
row[0][4]