Search code examples
pythondjangoviewmodelsrawsql

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


I am facing an issue while using raw SQL queries in Django.

In views.py, the following function is defined:

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

Is there something I am missing here ? How can I remove the unnecessary prefix and suffix from the returned value?


Solution

  • They are not prefixes and suffixes. The return value of .fetchall() is always a list of tuples, whether it returns a single value or multiple rows and columns. From the 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.

    That being said, you can return a single value from your function using something like this:

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