Python 原始 SQL 查询返回包含在 [('...'),] 中的值

Python Raw SQL query is returning values enclosed inside [('...'),]

我在 Django 中使用原始 SQL 查询时遇到问题。

在views.py中定义了以下函数:

def functionSQL():

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute('select column_name from "table_name" where CONDITION')
    value = cursor.fetchall()
    return value

The value is returned as
[('returned_value'),] instead of returned_value

我在这里遗漏了什么吗? 如何去除返回值中不需要的前缀和后缀?

它们不是前缀后缀.fetchall() 的 return 值始终是一个 元组列表 ,无论它 return 是单个值还是多个行和列。来自 docs:

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.

话虽这么说,您可以 return 从您的函数中使用类似这样的东西的单个值:

def functionSQL():
    ...
    value = cursor.fetchall()
    return value[0][0] if value != [] else value