问题
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