How to iterate over field values of objects?
In a django project I am trying to display the report like this:
Heading: Field1 Field2 Field3 of Type A Field3 of Type B
Data: Record1Value1 Record1Value2 Record1Value3
Record2Value1 Record2Value2 Record2Value3
Record3Value1 Record3Value2 Record3Value3
Of which Record1Value1 and Record2Value1, Record3Value1 belong to a list of values1. It is a list of field values of objects in model. The same with list values2. Record1Value3 and Record3Value3 belong to a list of values3, but filtered by type=’type A’. Record2Value3 belong to a list of values3, filtered by type=’type B’. So in my views.py I code like below:
objects=model.objects.filter(field=input,…)
values1=objects.values_list(field1, flat=True)
values2=objects.values_list(field2, flat=True)
objects3a= objects.filter(type=’type A’)
objects3b= objects.filter(type=’type B’)
values3a=objects3a.values_list(field3, flat=True)
values3b=objects3b.values_list(field3, flat=True)
functions=objects.values_list(type,flat=True)
In the html page, I use the following codes:
<th>
<td> field1</td> <td> field2</td> <td> field3 of type A</td> <td>field3 of typeB </td>
</th>
{%for value1 in values1%}
{%for value2 in values2%}
{%for value3a in values3a%}
{%for value3b in values3b%}
<tr>
<td> {{value1}}</td> <td> {{value2}}</td>
<td>
{%if function==’type A’%}
{{value3a}}
{%endif%}
</td>
<td>
{%if function==’type B’%}
{{value3b}}
{%endif%}
</td>
</tr>
{%endfor%}
{%endfor%}
{%endfor%}
{%endfor%}
What I want to do is iterate over each record and put the field values of each record in corresponding cell, but for field3, if the ‘type’ field of the record is ‘type A’ then put the field3 value in the column ‘field3 of type A’, and leave ‘field3 of type B’ blank. Vice versa to type B.
The problem is that it is not really looping over each record this way. The block of codes:
{%if function==’type A’%}
{{value3a}}
{%endif%}
does not really work because it does not recognize function and value3a belong to the same object: objects3a. Do I have to write a forms.py to do this? If so, how? (Note that I can not declare objects in forms.py because I have to get user input in views.py).
Also, is there any way to simplify the c开发者_C百科odes? These many forloops makes it almost impossible to load the data.
Hope someone could help me out!
It's hard to say for sure without all of the details of your model implementation, but you should be able to pass the objects
result directly to your template and work with it there.
Here's the idea:
<th>
<td> field1</td> <td> field2</td> <td> field3 of type A</td> <td>field3 of typeB </td>
</th>
{%for object in objects %}
<tr>
<td> {{object.field1}}</td> <td> {{object.field2}}</td>
<td>
{%if object.type==’type A’%}
{{object.field3}}
{%endif%}
</td>
<td>
{%if object.type==’type B’%}
{{object.field3}}
{%endif%}
</td>
</tr>
{%endfor%}
精彩评论