developerworks
developerworks

Reputation: 41

django queryset values() method fields order is different with returned

I have a field list to select,like this:

field_names = [u'name', u'mobile', u'address', u'email', u'sex'] 

render template with the following:

return render_to_string('templatetags/index.html', {
   'objects':User.objects.all().values(*field_names)
})

But the returned result field order is different with input field order is:

Ouput in template with {{ objects }}:

{u'mobile': u'18680868047', u'email': u'', u'sex': u'U', u'name': u'\u4f55\u667a\u5f3a', u'address': u'\u8944\u9633\u5357\u8def175\u53f7 \u73af\u4e2d\u5546\u53a6 410\u5ba4'}

This is my template:

<table>
{% for object in objects %}
<tr>
{% for key,value in object.items %}
   <td class="{{key}}">{{ value }}</td>{% endfor %}
</tr>
{% endfor %}
</table>

Upvotes: 4

Views: 5989

Answers (2)

developerworks
developerworks

Reputation: 41

i am using the OrderedDict collections object to resolve the fields ordering issue.

objects_list = []
for row in queryset:
    ordered_dict = collections.OrderedDict()
    for col in self.field_names:
        ordered_dict[col] = row[col]  
    objects_list.append(ordered_dict) 

Upvotes: 0

second
second

Reputation: 28637

queryset.values() returns a list of dicts, and dicts don't return their items in any particular order.

if you want your values in order, use queryset.values_list which returns a list of tuples.

(you will need to keep the list of columns in a separate context variable)

Upvotes: 7

Related Questions