You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中将PostgreSQL查询结果转为字典的报错求助

Fixing Dictionary Conversion for Django PostgreSQL Queries

Let's break down why you're running into these errors and walk through actionable solutions to get your query results as dictionaries.

Why the Errors Happen

  1. dictfetchall() not found: The dictfetchall() method is a Django-specific cursor utility, but when you're dealing with the raw psycopg2 cursor (either directly or via an unconfigured Django connection), it won't have this method.
  2. cursor_factory argument error: Django's connection.cursor() method doesn't accept the cursor_factory parameter directly — you need to access the underlying raw PostgreSQL connection to use psycopg2's cursor factories.

Solution 1: Use Django's Built-in dictfetchall()

If you're using a recent Django version, the wrapped cursor from connection.cursor() should have the dictfetchall() method built-in. Try adjusting your code like this:

from django.db import connection

def custom_query(query):
    cursor = connection.cursor()
    cursor.execute(query)
    # Use Django's built-in method to get results as dictionaries
    rows = cursor.dictfetchall()
    return rows

This works because Django wraps the database cursor and adds helper methods like dictfetchall() to convert results into dictionaries mapped by column names.


Solution 2: Use psycopg2's DictCursor (For PostgreSQL)

If you prefer using psycopg2's native dictionary cursor, you need to access the raw database connection from Django's wrapper. Here's how:

from django.db import connection
import psycopg2.extras

def custom_query(query):
    # Get the raw psycopg2 connection from Django's connection wrapper
    raw_conn = connection.connection
    # Create a DictCursor using the raw connection
    with raw_conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as dict_cursor:
        dict_cursor.execute(query)
        rows = dict_cursor.fetchall()
        # Convert DictRow objects to regular Python dictionaries (optional but cleaner)
        return [dict(row) for row in rows]

This approach uses psycopg2's native cursor to return rows as dictionary-like objects, which we then convert to standard Python dictionaries for consistency.


Solution 3: Manual Conversion (Database-Agnostic)

If you want a solution that works across all databases (not just PostgreSQL), you can manually map the query results to dictionaries using the cursor's column descriptions:

from django.db import connection

def custom_query(query):
    cursor = connection.cursor()
    cursor.execute(query)
    # Extract column names from the cursor's description
    column_names = [col[0] for col in cursor.description]
    # Pair each row's values with column names to create dictionaries
    return [dict(zip(column_names, row)) for row in cursor.fetchall()]

This method is universal — it doesn't depend on any database-specific extensions or Django helper methods, so it's safe to use no matter which database backend you're working with.


内容的提问来源于stack exchange,提问作者M.Sameh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:59:08