2014-04-14 31 views
0

所以說我有一個模型,其中有一些領域可能不被填充: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中執行此操作?我知道有一種將對象轉換爲字典的方法,但這並不能解決排除空字段的問題。由於

回答

2

可以使用model_to_dict方法,並逐一解釋是這樣的:

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

效果很好,謝謝。一個問題,是否有任何特定的方式來定義字段?因爲它們與我的模型中的順序不同。 –

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) 
相關問題