【发布时间】:2011-01-14 02:52:26
【问题描述】:
我有一个名为manor_stats 的数据库对象,有大约30 个字段。对于大多数行,这些字段中的大多数将为空。
在我的模板中,我想遍历行中的所有字段,并仅打印非空字段的信息。
例如,有一个名为“name”的字段:我只想在模板中为那些字段不为空的对象打印<li>Name: {{ manor_stats.name }}</li>。理想情况下,我也想自动从某处提取“名称:”,而不是指定它。
我知道我可以使用{% if manor_stats.name %} 来检查每个字段是否为空,但我不想对所有字段都这样做 30 次。
这是我在 views.py 中的内容:
manor_stats = Manors.objects.get(idx=id)
return render_to_response('place.html', { 'place' : place, 'manor_stats' : manor_stats }, context_instance = RequestContext(request))
然后在 place.html 中,我想要一些大致像这样工作的东西(伪代码,??? 表示我不知道该怎么做的位):
{% if manor_stats %}
<ul>
{% for manor_stats.property??? in manor_stats %}
{% if manor_stats.property %}
<li>{{ manor_stats.property.field_name??? }} {{ manor_stats.property.value??? }}</li>
{% endif %}
{% endfor %
{% endif %}
希望这是有道理的......
【问题讨论】: