本文介绍了如何在Django视图页面中显示外键数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Project ProjectFloorPlan 之间有关联,并且我想在模板中显示 ProjectFloorPlan 数据.请让我知道如何在模板中显示 ForeignKey 数据.

i have relation between Project and ProjectFloorPlan, and i want to display ProjectFloorPlan data in my template. Please let me know how i can display the ForeignKey data in my template.

这是我的 models.py 文件...

class Project(models.Model):
    name=models.CharField(max_length=225)
    slug=models.SlugField(null=True, unique=True)
   
    def __str__(self):
       return self.name


class ProjectFloorPlan(models.Model):
    project=models.ForeignKey('Project', related_name='projectfloorplan', on_delete=models.CASCADE, default=None)
    floorplan_image=models.ImageField(upload_to='floorplan_image')
    bhk=models.CharField(max_length=100)
    bed=models.CharField(max_length=100)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.project.name

这是我正在尝试的 project.html 文件,用于显示 ProjectFloorPlan 数据...但未显示任何内容

here is my project.html file where i am trying o display ProjectFloorPlan data...but it's displaying nothing

{% fot i in project.projectfloorplan_set.all %}
<tr>
    <td>{{i.bhk}}</td>
    <td>{{i.bed}}</td>
    
</tr>
{% endfor %}

推荐答案

由于已设置 related_name ='projectfloorplan',因此不必使用 _set 表示法来访问反向FK.

Since you have set related_name='projectfloorplan', you don't have to use _set notation to access the reverse FK.

因此,请使用 project.projectfloorplan.all 代替 project.projectfloorplan_set.all

{% fot i in project.projectfloorplan.all %}
<tr>
    <td>{{ i.bhk }}</td>
    <td>{{ i.bed }}</td>

</tr>
{% endfor %}

这篇关于如何在Django视图页面中显示外键数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 10:54