Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 791
developerworks Avatar asked Sep 02 '25 14:09

developerworks


1 Answers

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)

like image 197
second Avatar answered Sep 05 '25 07:09

second