title: Exporting to CSV/Excel file in django from using raw sql
body: <p>Am having issues generating excel/csv files in django mainly because am querying the database using raw sql(directly). I only have access to the database and not the model classes. Here is my code snippet.</p>
  <p>I get an Error <strong>'dict' object has no attribute 'todo_job'</strong></p>
  <h2>View code</h2>
  <pre><code>def query_to_dicts(query_string, *query_args):
  &quot;&quot;&quot;Run a simple query and produce a generator
  that returns the results as a bunch of dictionaries
  with keys for the column values selected.
  &quot;&quot;&quot;
      #log.debug(str(dir(connection)))
      cursor = connection.cursor()
      #log.debug(str(dir(cursor)))
      cursor.execute(query_string, query_args)
      #log.debug(cursor.rowcount)log
      col_names = [desc[0] for desc in cursor.description]
      #log.debug(str(col_names))
      while True:
          row = cursor.fetchone()
          if row is None:
              break
          
          row_dict = dict(izip(col_names, row))
          yield row_dict
      
      return
  
  def excel(request):
      todo_obj = query_to_dicts('''SELECT * FROM users''')
  
      response = HttpResponse(mimetype='application/ms-excel')
      response['Content-Disposition'] = 'attachment; filename=elagu.xls'
      wb = xlwt.Workbook(encoding='utf-8')
      ws = wb.add_sheet(&quot;Todo&quot;)
  
      row_num = 0
  
      columns = [
          (u&quot;ID&quot;, 6000),
          (u&quot;t_stamp&quot;, 8000),
      
      ]
  
      font_style = xlwt.XFStyle()
      font_style.font.bold = True
  
      for col_num in xrange(len(columns)):
          ws.write(row_num, col_num, columns[col_num][0], font_style)
          # set column width
          ws.col(col_num).width = columns[col_num][1]
  
      font_style = xlwt.XFStyle()
      font_style.alignment.wrap = 1
  
      for obj in todo_obj:
          row_num += 1
          row = [
              row_num,
              obj.todo_job,
              obj.created_date.strftime(&quot;%A %d. %B %Y&quot;),
          ]
          for col_num in xrange(len(row)):
              ws.write(row_num, col_num, row[col_num], font_style)
  
      wb.save(response)
      return response
  </code></pre>