如果我使用fetchall()命令,Django Python会显示奇怪的结果

2024-10-06 18:30:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了Django框架和MySQL数据库。我厌倦了在一行中显示全名,它在html页面上显示编码结果,如下所示。我试图在python上设置decode选项,但效果不好。如果我使用fetchone()命令,它将显示正确的单词。但是,如果使用fetchall()命令,它会显示不同的结果。你能看到错误吗

profile.py

cursor = connection.cursor()
cursor.execute("SELECT full_name FROM myapp_profile ORDER BY idx DESC")
results = cursor.fetchall()

x = cursor.description
resultsList = []   
for r in results:
    i = 0
    d = {}
    while i < len(x):
        d[x[i][0]] = r[i]
        i = i+1
    resultsList.append(d)

context = Context({'data' : resultsList })
return HttpResponse(loader.get_template('profile/profile_list.html').render(context))

html上的结果

{'full_name': u'\uae40\uc9c0\uc120'} 
{'full_name': u'\uc774\uc8fc\ud604'} 
{'full_name': u'\uae40\uae30\uc790'} 
{'full_name': u'\uae40\uae30\uc131'} 
{'full_name': u'\uae40\uc544\uc601'} 

Tags: djangoname命令框架htmlcontextmysqlprofile
1条回答
网友
1楼 · 发布于 2024-10-06 18:30:07

html代码是错误的

以前是这样的

{% if data %}
   There are {{ data|length }} records:
   {% for e in data %}
      <br />
      <td> {{ e }} </td>
      <br />
   {% endfor %}
{% else %}
   There are no records in the system
{% endif %}

我这样改变了它,它成功了

{% if data %}
   There are {{ data|length }} records:
   {% for e in data %}
      <br />
      <td> {{ e.full_name }} </td>
      <br />
   {% endfor %}
{% else %}
   There are no records in the system
{% endif %}

相关问题 更多 >