0

I have this VIEW below:

from django.shortcuts import render
from django.db import connections
def IndexView(request):
    con_totvs = connections['totvs'].cursor()
    with con_totvs as cursor:
        cursor.execute("SELECT A1_NOME, A1_CGC FROM SA1010 WHERE D_E_L_E_T_ <> '*' ORDER BY A1_NOME")
        select = cursor.fetchall()
        # bla bla bla
        context = {}
        cursor.close ()
    con_totvs.close ()
    return render(request, "home.html", context)

Just like I use when creating models, in my template id like to do something like:

{% for i in SELECT %}
   {{ i.A1_NOME }}
{% endfor %}

Is this possible? Ive been searching but i failed it

Edit:

print(select)
>>[('NAME_PERSON1', 'COD_PERSON1'), ('NAME_PERSON2', 'COD_PERSON2'), ...]

1 Answers1

0

Turns out i needed to declare the field names and pass that to a dict. I was helped through this link: MySQL: Get column name or alias from query

def IndexView(request):
    con_totvs = connections['totvs'].cursor()

    with con_totvs as cursor:
        cursor.execute("SELECT A1_NOME, A1_CGC FROM SA1010 WHERE D_E_L_E_T_ <> '*' ORDER BY A1_NOME")
        fields = [field_name[0] for field_name in cursor.description]
        select = [dict(zip(fields,row)) for row in cursor.fetchall()]
        # get specific field
        nome = (row['A1_NOME'] for row in select)

        cursor.close ()
    con_totvs.close ()

    return render(request, "home.html", {'select': select})

Now i can use

{% for i in select %}
{{i.A1_NOME}} - {{i.A1_CGC}}
{% endfor %}
Dharman
  • 30,962
  • 25
  • 85
  • 135