如何在 Django 中使用默认连接从 Select 查询中获取键(列名)-值对



我在一个 Django 项目中有 4 个应用程序。我正在使用默认的 Postgres 数据库连接,我已将其包含在我的setting.py文件中。

对象django.db.connection表示默认数据库连接。为了使用数据库连接,我调用connection.cursor()来获取游标对象。然后,我调用cursor.execute(sql, [params])来执行原始 Postgres 查询,并cursor.fetchone()cursor.fetchall()返回生成的行。

现在,在一个应用程序中,我想使用 (connection.cursor(cursor_factory = psycopg2.extras.RealDictCursor)( 获取(key(column name), value)对中的记录,该记录由psycopg2.connect提供,但我拥有的默认连接与cursor_factory = psycopg2.extras.RealDictCursor不兼容。

如何使用默认连接从数据库中获取(key(column name), value)对?
在 setting.py

`DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',      
'OPTIONS' : {
'options': '-c search_path=django,public'
},
'NAME': 'postgres',
'USER': 'abc',
'PASSWORD': 'password!',
'HOST': '',
'PORT': '',
}
}
`

在 python 文件中.py

from django.db import connection
cur = connection.cursor(cursor_factory = psycopg2.extras.RealDictCursor) 
cur.execute("SELECT * FROM sometable") 
data= cur.fetchall()

ERROR: cursor() got an unexpected keyword argument 'cursor_factory'

您必须获得一个底层的 postgres 连接,确保它已建立,然后您可以指定自定义cursor_factory。

from django.db import connections
import psycopg2

def scan_tables(app):
conn = connections['default']
conn.ensure_connection()
with conn.connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cursor:
cursor.execute("SELECT table_name, column_name "
"FROM information_schema.columns AS c "
"WHERE table_name LIKE '{}_%'".format(app))
print(cursor.fetchall())

scan_tables('django')

这是 https://stackoverflow.com/a/48844401/803174 @kert只是放置不同的光标类型的改编答案。

最新更新