Django 模板:循环并打印对象的所有可用属性? [英] Django templates: loop through and print all available properties of an object?

查看:18
本文介绍了Django 模板:循环并打印对象的所有可用属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 manor_stats 的数据库对象,大约有 30 个字段.对于大多数行,这些字段中的大多数将为空.

I have a database object called manor_stats, with around 30 fields. For most rows, most of these fields will be null.

在我的模板中,我想遍历行中的所有字段,并仅打印非空字段的信息.

In my template, I'd like to loop through all the fields in the row, and print info for only the fields that aren't null.

例如,有一个名为name"的字段:我想在模板中打印 <li>Name: {{ manor_stats.name }}</li> 仅用于那些字段不为空的对象.理想情况下,我也想从某个地方自动引入名称:",而不是指定它.

For example, there's a field called "name": I'd like to print <li>Name: {{ manor_stats.name }}</li> in the template ONLY for those objects where the field isn't null. Ideally I'd like to pull in "Name: " from somewhere automatically too, rather than specifying it.

我知道我可以使用 {% if manor_stats.name %} 来检查每个字段是否为空,但我不想对所有字段都这样做 30 次.

I know I could use {% if manor_stats.name %} to check whether each field is null, but I don't want to do that 30 times for all the fields.

这是我在 views.py 中的内容:

Here's what I have in 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 中,我想要一些类似这样的东西(伪代码,用 ??? 表示我不知道该怎么做的部分):

And then in place.html, I'd like to have something that works approximately like this (pseudocode, with ??? indicating the bits that I don't know how to do):

{% 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 %}

希望这是有道理的...

Hope that makes sense...

推荐答案

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

You could add a method to your Manors model that will return all the field values, from there you can just loop over these values in your template checking to see if the value isn't null.

--models.py

-- models.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

-- manor_detail.html

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

这篇关于Django 模板:循环并打印对象的所有可用属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆