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 Answer 1

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 %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.