can i control select column order in a queryset?

Skip to first unread message

Joe Linoff

Jun 25, 2011, 6:39:24 PM6/25/11
Hi Folks:

I am a newbie who is really enjoying Django. It is a great system and has really saved me a lot of time but I am having a problem trying to control the column order in a queryset.

In SQL my queries would look something like this:

      -- column order #1
      SELECT 'Third','Second',First' FROM test ORDER BY 'Third' ASC;
      -- column order #2
      SELECT 'First','Third','Second' FROM test ORDER BY 'First' ASC;

In Django 1.3 I am doing this:

    # column order #1
    data = test.objects.values('Third','Second','First').order_by('Third').all()
    data = test.objects.values('Third','Second','First') # tried this as well

    # column order #2
    data = test.objects.values('First','Third','Second').order_by('First').all()
    data = test.objects.values('First','Third','Second') # tried this as well

Unfortunately, the columns are always returned in the same order.

What am I doing wrong? I am trying to do something that isn't supported?



Karen Tracey

Jun 26, 2011, 12:04:05 AM6/26/11
The calls you are showing returns lists of dictionaries. Dictionaries have no specified order.

The order_by call you've tried in a couple of places orders the elements in the lists, based on the values in the specified columns. It has nothing to do with "column order".

If you describe what you are trying to achieve someone might be able to help. You should not be caring about "column order" when using Django.


Joe Linoff

Jun 30, 2011, 9:05:17 PM6/30/11
Hi Karen:

Thank you for your response. The reason that I care about about column order is so that I can use the same template for different queries with arbitrary column orders using a single variable. I would like to be able to extract the field key name and use them directly in the column header. Perhaps something like this:

01 {% extends "base.html" %}
03 {% block head %}{{title}}{% endblock %}
05 {% block content %}
06   {% if rows %}
07     <table class="cls1 cls2">
08        {% for row in rows %}
09          {% if forloop.first %}
11             <tr class="cls3">
12               <!-- The headers -->
13               {% for key,val in row %}
14                  <th class="cls4">key</th>
15               {% endfor %}
16             </tr>
18             {% cycle even odd as rc %}
19             <tr class="cls5 {{rc}}">
20               {% for key,val in row %}
21                 <td class="cls6">val<td>
22               {% endfor %}
23             </tr>
24          {% endfor %}
25        {% endfor %}
26     </table>
27   { %endif }
28 {% endblock %}

Instead, what I am doing now is I am manually adding the column titles as a separate template variable.



Reply all
Reply to author
0 new messages