django 内容类型和字符串比较

aem*_*mdy 2 django content-type django-templates

我有一个包含 ContentType 字段的模型。

在任何模型方法中,我都可以将其与字符串进行比较:

self.content_type == "construction" # True if ContentObject points to Construction model.
Run Code Online (Sandbox Code Playgroud)

但是,这样的事情似乎在模板中不起作用。

我尝试的第一件事

{% if object.content_type == "construction" %}
Run Code Online (Sandbox Code Playgroud)

第二:

def __unicode__(self): 
    return str(self.content_type)
`{% if object == "construction" %}`
Run Code Online (Sandbox Code Playgroud)

它是错误的,但是 {{ object }} 打印construction.

Ala*_*air 5

unicode 方法ContentType只显示名称,这就是为什么要{{ object }}显示construction在模板中。

class ContentType(models.Model):
    ...
    def __unicode__(self):
        return self.name
Run Code Online (Sandbox Code Playgroud)

但是,object.content_type是一个ContentType实例,而不是一个字符串,因此将它与“构造”进行比较将始终返回False. 尝试比较内容类型model

{% if object.content_type.model == "construction" %}
Run Code Online (Sandbox Code Playgroud)