4

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>

2 Answers 2

7

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.