Search code examples
djangofilterparent-childmodels

Django filter child by parent


I'm trying to filter children by its parent in my templates. Example being I have houses that are displayed and want to display their amenities(children) along with them. When I try and do so each house list all amenities for every house. How would I make is so that I list a house and only its amenities?

Here are my models:

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)

In my views I am trying to filter the child by its parent:

def index(request):
    home = Home.objects.filter()
    amenities = Amenities.objects.filter(home=home)

    return render(request, 'home/home.html', {'home': home, 'amenities': amenities})

In my template I am try and loop through each home and their amenities like so:

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

thank you


Solution

  • I think you are looking for this

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