Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying models in django (two levels deep)

Tags:

python

django

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?

like image 651
Robert Johnstone Avatar asked Mar 21 '13 16:03

Robert Johnstone


People also ask

How can you combine multiple QuerySets in a view?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function.

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.

What is __ Str__ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What is def __ str __( self in Django?

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.


1 Answers

This should do the trick:

town_id = 5
houses_in_town = House.objects.filter(street__town__id = town_id)
like image 73
Krystian Cybulski Avatar answered Oct 14 '22 17:10

Krystian Cybulski