比较 Django 模板中的对象字段

Compare object field in Django template

我有模型

class Applicant(models.Model):
    job = models.ForeignKey(Job)
    location = models.ForeignKey(Location)
    type = models.ForeignKey(Type)

其中 type 指的是另一个 table:

class Type(models.Model):
    """ Model for Applicant Type

    Attributes:
        type: string
    """

    type = models.CharField(max_length=45)

    def __str__(self):
        """ Override for __str__ method
        """
        return self.type

    class Meta:
        managed = False
        db_table = 'jobs_type'

我可以通过简单地编写以下内容来访问模板中的对象类型:

<h3>{{applicant.type}}</h3>

其中applicant是申请人对象。但是,当我尝试将该类型与字符串进行比较时,比较失败:

{% if applicant.type == "Driver" %}
    <h3>{{applicant.type}}</h3>
{% else %}
    <h3>{{applicant.type}} does not equal "Driver"</h3>
{% endif %}

正在打印:

Driver does not equal "Driver"

有没有更好的方法来比较 Django 模板中的对象字段?

数据库jobs_typetable中的"Type"字段是一个varChar。

推测 "Driver" 在 Type 模型实例的 type 字段中。因此您可以与该字段进行比较。

{% if applicant.type.type == "Driver" %}