Robert Johnstone
Robert Johnstone

Reputation: 5371

Querying models in django (two levels deep)

If I have the following tables

class Town(models.Model):
    created = models.DateTimeField()

class Street(models.Model):
    town = models.ForeignKey(Town)
    created = models.DateTimeField()

class House(models.Model):
    street = models.ForeignKey(Street)
    created = models.DateTimeField()

How do I get all the Houses in a Town if I have the name/id of the town?

Upvotes: 8

Views: 2778

Answers (1)

Krystian Cybulski
Krystian Cybulski

Reputation: 11108

This should do the trick:

town_id = 5
houses_in_town = House.objects.filter(street__town__id = town_id)

Upvotes: 17

Related Questions