(env)$ vi .env# PostgreSQLPOSTGRES_ENGINE=django.db.backends.postgresql_psycopg2POSTGRES_DATABASE=5952POSTGRES_USER=postgresPOSTGRES_PASSWORD=POSTGRES_HOST=127.0.0.1POSTGRES_PORT=5432
from django.db import connectiontry: cursor = connection.cursor() cursor.execute("SELECT * FROM database") col_names = [desc[0]for desc in cursor.description] # カラム名取得# fetchall()で、結果を全て取り出せる rows = cursor.fetchall() dict_result = []for row in rows: row_dict =dict(zip(col_names, row)) dict_result.append(row_dict)exceptExceptionas e:raiseException()finally: cursor.close()return dict_result
外部のデータベースにアクセスする場合
import psycopg2import psycopg2.extras # DictCursorを使用するために拡張機能をimport# Connect to an existing databasetry: connection = psycopg2.connect("dbname='database' user='postgres' host='localhost' password='xxxxx' port='5432'") connection.autocommit =Trueexcept psycopg2.Error as e:raiseException()try:# Open a cursor to perform database operations cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)# Query the database and obtain data as Python objects cursor.execute("SELECT * FROM database")# fetchall()で、1結果を全て取り出せる cursor = cursor.fetchall() dict_result = []for row in rows: dict_result.append(dict(row))except psycopg2.Error as e:raiseException()finally: cursor.close() connection.close()return dict_result