我有一個具有此表結構的簡單資料庫:
----------------
| A1 | A2 | A3 |
|--------------|
| B1 | B2 | B3 |
| C1 | C2 | C3 |
----------------
使用此功能和djangorestframwork:
@api_view(['GET'])
def read(request, source):
if source not in sources:
return Response({'error': f'{source} not found', 'allowed sources': sources, 'help': address})
with connect(f'{source}/news.db') as conn:
cmd = '''SELECT * FROM newstable'''
cur = conn.execute(cmd)
results = cur.fetchall()
rand_id = randrange(len(results))
return Response(results[rand_id])
內容顯示json如下:
[
'B1',
'B2',
'B3
]
但是,我想得到這個:
{
'A1': 'B1',
'A2': 'B2',
'A3': 'B3
}
uj5u.com熱心網友回復:
這是來自 Django檔案:
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()
]
所以你可以替換這個:
results = cur.fetchall()
有了這個:
results = dictfetchall(cur)
另一種選擇是使用psycopg2.extras.DictCursor.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422004.html
標籤:
