2012-04-04 59 views
2

我有一個ContentType字段的模型。django contenttype和字符串比較

在任何模型的方法,我可以把它比作字符串:

self.content_type == "construction" # True if ContentObject points to Construction model. 

然而,這樣的事情似乎並沒有在模板中工作。

第一件事,我想

{% if object.content_type == "construction" %} 

其次:

def __unicode__(self): 
    return str(self.content_type) 
`{% if object == "construction" %}` 

,它是假的,但{{對象}}打印construction

+2

嘗試:{{if if object.content_type.model ==「construction」%}' – 2012-04-04 13:06:23

回答

4

ContentType的unicode方法只顯示名稱,這就是爲什麼{{ object }}在模板中顯示爲construction的原因。

class ContentType(models.Model): 
    ... 
    def __unicode__(self): 
     return self.name 

然而,object.content_typeContentType實例,而不是一個字符串,所以比較爲「建設」總是返回False。請嘗試比較內容類型的model

{% if object.content_type.model == "construction" %}