在html表中模板化直接原始查询

时间:2018-04-10 16:10:51

标签: python html django django-templates

我是django的初学者,我正在使用只读数据库,我只是想做一些选择并在我的模板中将其显示为一个表格,但是我不能通过列将coulmn返回到我的html表中,帮助我, 我正在使用directky原始查询

Model.py     来自django.db导入连接

# Create your models here.
def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
]


def my_custom_sql(self):
    with connection.cursor()as cursor:
        cursor.execute("""
                       SELECT EQUIP_ID, LINE_CODE, PLANT_CODE 
                       FROM tbs_rm_mnt_shift_sumr 
                       where SUMR_YMD = '20180405' AND SIDE_CODE = 'T' AND 
                       rownum < 20
                       """ )
        row = dictfetchall(cursor)
        return row

view.py

from django.shortcuts import render, redirect, get_object_or_404
from .models import my_custom_sql


# Create your views here.

def show_list(request):
   query= my_custom_sql(self='my_custom_sql')
    return render(request,'monitoring.html', {'query': query})

monitoring.html

    <table border="2" style="solid black">
     <tr>
        <td>Equip</td>
        <td>Line</td>
        <td>Plant</td>

        {% for instance in query %}
            {% for field, value in instance.items %}

                <tr>
                    <td>{{ value }} </td>

                </tr>
            {% endfor %}
        {% endfor %}
     </tr>
    </table>

浏览器输出: enter image description here

1 个答案:

答案 0 :(得分:0)

目前,您只为每行输出一个td

{% for instance in query %}
  {% for field, value in instance.items %}
    <tr>
      <td>{{ value }} </td>
    </tr>
  {% endfor %}
{% endfor %}

听起来应该在tr标签内循环:

{% for instance in query %}
    <tr>
      {% for field, value in instance.items %}
      <td>{{ value }} </td>
      {% endfor %}
    </tr>
{% endfor %}

但是,您不能假设字典中键的顺序,因此您应该按键访问项目,或者重新考虑是否要使用dictfetchall

{% for instance in query %}
    <tr>
      <td>{{ instance.EQUIP_ID }} </td>
      <td>{{ instance.LINE_ID }} </td>
      <td>{{ instance.PLANT_CODE }} </td>
      {% endfor %}
    </tr>
{% endfor %}