Search code examples
pythondjangopostgresqldjango-viewsexport-to-excel

Export RawQuerySet to excel with ExcelResponse. Error "ExcelResponse requires a sequence of sequences"


I try to download a view postgres to excel, it is possible with ExcelResponse ?

from excel_response import ExcelResponse
def vw_export_to_Excel(request):
    data = _Custumer.objects.raw('''select * from vw_customer''')
    return ExcelResponse(data, 'customer')

Solution

  • Iterating the return value of the raw method yields model instances, not a sequences.

    Use django.db.connection.cursor() + .execute to get what you want.

    from django.db import connection
    from excel_response import ExcelResponse
    
    def vw_export_to_Excel(request):
        cursor = connection.cursor()
        cursor.execute("select * from vw_customer")
        return ExcelResponse(cursor.fetchall())
    

    Or, use values_list:

    from excel_response import ExcelResponse
    
    def vw_export_to_Excel(request):
        data = list(_Custumer.objects.values_list())
        return ExcelResponse(data, 'customer')