Get grandchildren of an object with django

1.9k Views Asked by At

I'm building a webapp with django with the following models:

class Business(models.Model):
    ...

class Branch(models.Model):
    business = models.ForeignKey(Business)
    ...

class Event(models.Model):
    branch = models.ForeignKey(Branch)

My questions is how can I get all events by their business (not their branch), and if it possible to do so in a DB query.

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

Django querysets allow you to use the "__" notation to access relationships. You can take it to any depth and read more about it here.

Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want.

Any of the following should work in your case:

Event.objects.filter(branch__business=<business>)
Event.objects.filter(branch__business_id=<business-id>)
Event.objects.filter(branch__business__id=<business-id>)
# if business had a name field you could also use
Event.objects.filter(branch__business__name=name-of-business)