I’m trying to loop through a queryset to built a dictionary, then loop through that dictionary in my template to create a grid. It works, BUT, the fields are in the wrong order. Instead of getting them in the order of Field1 Field2 Field3, I get Field2, Field1, Field3. This is just an example of whats happening. In actuality I have 10 fields, but they’re not rendered in the same order I defined the model with. Can anyone help explain why and what I can do to fix so that the order stays consistent?
models.py:
class MyModel(models.Model)
Field1 = models.CharField(max_length=30)
Field2 = models.DateTimeField()
Field3 = models.CharField(max_length=30)
views.py:
def MyView(request):
MyQuerySet = MyModel.objects.all()[:10]
MyDictionary = {}
RowNumber = 0
for row in MyQuerySet:
NestedDictionary = {}
ColumnNumber = 0
for column in row._meta.fields:
if column.verbose_name != "ID":
fieldtype = str(type(column)).replace("'>", "").replace("<class 'django.db.models.fields.", "")
NestedDictionary.update({str(ColumnNumber):
{'name': column.verbose_name,
'value': getattr(row, column.verbose_name),
'type': fieldtype}
})
ColumnNumber = ColumnNumber + 1
MyDictionary.update({str(RowNumber): NestedDictionary})
RowNumber = RowNumber + 1
ctx = {}
ctx.update({'MyDictionary':MyDictionary})
return render_to_response('MyTemplate.html', ctx, context_instance=RequestContext(request))
MyTemplate.html:
<table cellpadding="1px" cellspacing="1px" border="1px">
{% for key, row in MyDictionary.items %}
<tr>
{% for key2, field in row.items %}
<td>
{{ field.value }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>