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 House
s in a Town
if I have the name/id of the town?
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.
Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
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.
This should do the trick:
town_id = 5
houses_in_town = House.objects.filter(street__town__id = town_id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With