2012-04-04 58 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" %}