title: Grouping results from SQL query in python to display on page
body: <p>I am running an SQL query in a views.py file and based on what values are returned I need to display different data in a column from an .html file.  </p>
  
  <p>If:</p>
  
  <p>customer_id is not null, then the detail column should display the customer_id and name.</p>
  
  <p>If:</p>
  
  <p>customer_id is null, then the detail column should display the department name and description.</p>
  
  <p>So, there are numbers in a database.  Some are assigned to a customer, and some are assigned to a department. The basic purpose of the table is to show a list of numbers and what they are assigned to.</p>
  
  <pre><code>@render_to('customer/available_numbers.html')
  def AvailableNumbers(request):
      cur = NumberList()
  
      sql = '''
          SELECT
              cpt.number,
              cpt.call_type,
              cpt.customer_id,
              cpt.profile_id
              c.name,
              pro.department_name,
              pro.description
          FROM customerphonetable AS cpt
          LEFT OUTER JOIN customer AS c
          ON (cpt.customer_id = c.customer_id)
          LEFT OUTER JOIN profile AS pro
          ON (cpt.profile_id = pro.profile_id)
          WHERE cpt.number IS NOT NULL
          '''
  
      cur.execute(sql)
  
      rows = [dictify(row) for row in cur]
  
      return dict(rows=rows, cnt=len(rows))
  
  def dictify(row):
      return dict(zip([cd[0] for cd in row.cursor_description], row))
  </code></pre>
  
  <p>NumberList() connects to the database.</p>
  
  <p>The html file is set up to display the data like this:</p>
  
  <pre><code>{% block content %}
  &lt;table class ="table table-striped table-bordered"&gt;
      &lt;thead&gt;
          &lt;tr&gt;
              &lt;th&gt;Phone Number&lt;/th&gt;
              &lt;th&gt;Call Type&lt;/th&gt;
              &lt;th&gt;Detail&lt;/th&gt;
          &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody&gt;
      {% for row in rows %}
          &lt;tr&gt;
              &lt;td&gt;{{ row.number }}&lt;/td&gt;
              &lt;td&gt;{{ row.call_type }}&lt;/td&gt;
              &lt;td&gt;{{ ???? }}&lt;/td&gt;
          &lt;/tr&gt;
      {% endfor %}
      &lt;/tbody&gt;
  &lt;/table&gt;
  </code></pre>
  
  <p>I have tested the SQL query and it is pulling the correct data from the database.  I am getting lost on how to filter the results and correctly display the output based on the criteria.  </p>
  
  <p>Any suggestions?  If I am missing any info, please let me know.  Thank you.</p>