Django 模板 : loop through and print all available properties of an object?

标签 django django-templates

我有一个名为 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 %}

希望这是有道理的...

最佳答案

您可以向 Manors 模型添加一个方法,该方法将返回所有字段值,从那里您可以在模板中循环遍历这些值,检查该值是否不为空。

-- 模型.py

class Manors(models.Model)
  #field declarations

  def get_fields(self):
    return [(field.name, field.value_to_string(self)) for field in Manors._meta.fields]

-- manor_detail.html
{% for name, value in manor_stats.get_fields %}
  {% if value %}
    {{ name }} => {{ value }}
  {% endif %}
{% endfor %}

关于Django 模板 : loop through and print all available properties of an object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2217478/

相关文章:

python - Django:为特定模型的 `QuerySet`对象提供自定义过滤方法

python - 如何过滤 django grappelli 中的自动完成结果?

python - 如何在ajax中使用django url?

django - 无效的 block 标记 : 'render_field' , 应为 'empty' 或 'endfor' 。您是否忘记注册或加载此标签?

Django - 生产中的内存sqlite

python - Django 将选定的对象从表单传递到另一个表单

python - 用于按类别生成产品的模板过滤器

python - 在 Django 模板中显示抓取的结果

python - 仅当之前未插入分隔符时才插入分隔符

python virtualenv 无法访问主目录中的文件