Dictionary Raw SQL Queries Django

Python Django

Bagaimana cara membuat dictionary pada raw SQL query django ?

pertama import library django connection

from django.db import connections
cursor = connections['default'].cursor()

 

kedua buat function untuk merubah index menjadi dictionary

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
        ]

 

ketiga buat function untuk memanggil data dari database

def p_mapping_list(request):
    try:
        cursor.execute("""SELECT id, parent_id FROM test LIMIT 2""")
        all_list = dictfetchall(cursor)
        for p in all_list: 
            print(p.parent_id)
    except:
        cursor.close()
        connections['default'].cursor()

 

link dokumentasihttps://docs.djangoproject.com/en/1.11/topics/db/sql/

good luck …!

 

mm

Alfin F

Technopreneur , Developer, Advisor

More Posts

Follow Me:
TwitterLinkedIn