【问题标题】:Compare object field in Django template比较 Django 模板中的对象字段
【发布时间】:2015-03-23 16:06:17
【问题描述】:

我有模特

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

type 指的是另一个表:

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_type表中的“Type”字段是一个varChar。

【问题讨论】:

    标签: python django django-templates django-views


    【解决方案1】:

    大概“驱动程序”在 Type 模型实例的 type 字段中。因此,您可以与该字段进行比较。

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

    【讨论】:

    • 这更有意义!谢谢,我知道我错过了一些愚蠢的东西。
    猜你喜欢
    • 2016-02-24
    • 1970-01-01
    • 2012-06-06
    • 2011-08-18
    • 2019-01-19
    • 1970-01-01
    • 2022-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多