Django - 在if语句的django模板中获取外键字段名称

时间:2016-05-31 09:45:21

标签: python django

在我的模板中,我有一个if语句来检查文件的类型,但是file_type字段是一个外键对象。如何获取要在if语句中使用的file_type.type字段?

模板:

{% for file in Site.sitefiles_set.all %}
    {% if file.file_type != 'Site Plan' %}

模型:

class SiteFileType(models.Model):
    type = models.CharField(max_length=200)

    class Meta:
            verbose_name = "File Type"
            verbose_name_plural = "File Type"    

    def __unicode__(self):
        return self.type

class SiteFiles(models.Model): 
    showroom_config_data = models.ForeignKey(ShowroomConfigData,verbose_name="Showroom")
    major_site_info = models.ForeignKey(MajorSiteInfoData,verbose_name="Major Site")  
    site_image = models.ImageField(blank=True,upload_to=site_files_path)
    site_file = models.FileField(blank=True,upload_to=site_files_path)     
    file_name = models.CharField(max_length=200,verbose_name="File Name (Optional)",blank=True)
    file_type = models.ForeignKey(SiteFileType)

    class Meta:
            verbose_name = "Site Files"
            verbose_name_plural = "Site Files"

    def __unicode__(self):
        return '%s | %s ' % (self.showroom_config_data.location, self.major_site_info.location)

2 个答案:

答案 0 :(得分:2)

您只需将type附加到您已经拥有的变量(SiteFileType对象):

{% for file in Site.sitefiles_set.all %}
    {% if file.file_type.type != 'Site Plan' %}
    ...
    {% endif %}
{% endfor %}

答案 1 :(得分:2)

再按一点点跟随。

 {% if file.file_type.type != 'Site Plan' %}