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

查看:1234
本文介绍了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.

在我的模板中,我想循环遍历行中的所有字段,并只打印不为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.

我知道我可以使用 {%如果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 %}

希望有意义...

推荐答案

您可以向您的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天全站免登陆