我在mysql数据库中有十条记录,并且正在使用fetchall()
方法
现在,我需要使用Django中的sql查询在json中显示所有数据库结果。
当我运行下面的代码时,它只显示第一个记录,而其余的不显示。
我想知道为什么尽管使用 fetchall()方法
却只得到一个json记录这是代码
from django.db import connection
def read(request):
sql = 'SELECT * from crud_posts'
with connection.cursor() as cursor:
cursor.execute(sql)
output = cursor.fetchall()
print(output[0])
items=[]
for row in output:
items.append({'id':row[0], 'title': row[1],'content': row[2]})
jsondata = json.dumps({'items': items})
return HttpResponse(jsondata, content_type='application/json')
答案 0 :(得分:2)
第一次迭代后,您将退出for循环...修正您的标识:
from django.db import connection
def read(request):
sql = 'SELECT * from crud_posts'
with connection.cursor() as cursor:
cursor.execute(sql)
output = cursor.fetchall()
print(output[0])
items=[]
for row in output:
items.append({'id':row[0], 'title': row[1],'content': row[2]})
jsondata = json.dumps({'items': items})
return HttpResponse(jsondata, content_type='application/json')