Django ContentType和字符串比较

3
我可以为您翻译此内容,该模型中包含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" %}`

它是False,但{{ object }}打印出construction


2
尝试:{% if object.content_type.model == "construction" %} - Timmy O'Mahony
1个回答

7
< p > ContentType 的 Unicode 方法仅显示名称,这就是为什么模板中的{{ object }} 显示 construction 的原因。

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

然而,object.content_type 是一个 ContentType 实例,而不是字符串,因此将其与 "construction" 进行比较将始终返回 False。请尝试比较内容类型的 model

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接