开发者

Django: Printing a queryset dynamically in the template

How can I print the columns specified in "fields_i_want" instead of hardcoding the column names in the template code?

# 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 i开发者_开发技巧n 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>


See this SO question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜