我试图通过模板中的父级过滤子项。例如,我有房子显示,并希望与他们一起显示他们的设施(儿童)。当我尝试这样做时,每个房子都列出了每个房子的所有设施。我怎么做才能列出一个房子,只有它的设施?
以下是我的模特:
class Home(models.Model):
name = models.CharField(max_length=255)
photo = models.ImageField()
def __str__(self):
return self.name
class Amenities(models.Model):
home = models.ForeignKey(Home)
amenities = models.CharField(max_length=255)
在我的观点中,我试图通过其父级过滤孩子:
def index(request):
home = Home.objects.filter()
amenities = Amenities.objects.filter(home=home)
return render(request, 'home/home.html', {'home': home, 'amenities': amenities})
在我的模板中,我试着循环遍历每个家庭及其设施,如下:
{% for house in home %}
<div class="row">
<div class="col-md-6 portfolio-item">
<a href="house1.html">
<img class="img-responsive" src=" media/{{ house.photo }}" alt="">
</a>
<h3>
<a href="house1.html">House</a>
</h3>
<ul>
{% for i in amenities %}
<li>{{ i.amenities }}</li>
{% endfor %}
</ul>
</div>
</div>
{% endfor %}
谢谢
答案 0 :(得分:1)
我认为你正在寻找这个
{% for house in home %}
<div class="row">
<div class="col-md-6 portfolio-item">
<a href="house1.html">
<img class="img-responsive" src=" media/{{ house.photo }}" alt="">
</a>
<h3>
<a href="house1.html">House</a>
</h3>
<ul>
{% for i in house.amenities_set.all %}
<li>{{ i.amenities }}</li>
{% endfor %}
</ul>
</div>
</div>
{% endfor %}