Django:在模板中动态打印查询集

时间:2009-11-02 19:47:57

标签: django dynamic templates django-queryset

如何打印“fields_i_want”中指定的列,而不是在模板代码中对列名进行硬编码?

# Let's say I have this in my view:
foo = Foo.objects.filter(some_field='bar').select('field1', 'field2', 'field3')
fields_i_want = ['field1', 'field2']

# Then in the template I want to do something like this:
<TABLE id="some_id">    
    <TBODY>
        {% for row in some_var.foo %}
        <tr>
         {% for value in another_var.fields_i_want %}
            <td>{{ row[value] }}</td>
         {% endfor %}
        </tr>
        {% endfor %}
    </TBODY>
</TABLE>

# Instead of doing this:
<TABLE id="some_id">    
    <TBODY>
        {% for row in some_var.foo %}
        <tr>
            <td>{{ row.field1 }}</td>
            <td>{{ row.field2 }}</td>
        </tr>
        {% endfor %}
    </TBODY>
</TABLE>

1 个答案:

答案 0 :(得分:0)

请参阅this SO question