Ofersto
Ofersto

Reputation: 127

Get grandchildren of an object with django

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!

Upvotes: 5

Views: 2003

Answers (1)

pragman
pragman

Reputation: 1644

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)

Upvotes: 9

Related Questions