Django - 如何显示对象的字段名称和属性,不包括null?

时间:2014-04-14 12:11:02

标签: python django

所以说我有一个模型,其中有一些字段可能没有填写:

class Thing(models.Model):
    name = models.CharField(max_length=300)
    location = models.CharField(blank=True)
    comment = models.Charfield(blank=True)
    gallery = models.ForeignKey(SomeOtherThing, related_name='things')

我需要一种方法来在模板中显示有关此对象实例的信息,显示字段名称及其值(仅在填写时),如下所示:

The page with the thing on it

name: my awesome thing
location: wisconsin
comment: love this thing!
uploader: joe schmoe

例如,如果没有填写注释,我只想显示没有字段名称和空白值的字段:

The page with the thing on it 
name: my awesome thing
location: wisconsin
uploader: joe schmoe

在django中有没有某种方法可以做到这一点?我知道有一种方法可以将对象转换为dict,但这并不能解决排除空字段的问题。感谢

2 个答案:

答案 0 :(得分:2)

您可以使用model_to_dict方法,并按照以下方式迭代字典:

{% for key, value in dictionary.items %}
  {% if value %}
    <p>{{ key }}: {{ value }}</p>
  {% endif %}
{% endfor %}

答案 1 :(得分:0)

thing = Thing.objects.get(pk=1)
for field_name in Thing._meta.get_all_field_names():
    if getattr(thing, field_name):
        print field_name, getattr(thing, field_name)