How to display Foreign key Data in Django view page?

て烟熏妆下的殇ゞ 提交于 2021-01-29 14:01:33

问题


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.

Here is my models.py file...

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

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 %}

回答1:


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

So, use project.projectfloorplan.all instead of project.projectfloorplan_set.all

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

</tr>
{% endfor %}


来源:https://stackoverflow.com/questions/63497988/how-to-display-foreign-key-data-in-django-view-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!