Django中将PostgreSQL查询结果转为字典的报错求助
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
dictfetchall()not found: Thedictfetchall()method is a Django-specific cursor utility, but when you're dealing with the rawpsycopg2cursor (either directly or via an unconfigured Django connection), it won't have this method.cursor_factoryargument error: Django'sconnection.cursor()method doesn't accept thecursor_factoryparameter directly — you need to access the underlying raw PostgreSQL connection to usepsycopg2'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

