使用 Django 获取对象的孙子

Get grandchildren of an object with django

我正在使用具有以下模型的 django 构建一个网络应用程序:

class Business(models.Model):
    ...

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

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

我的问题是如何通过他们的业务(而不是他们的分支机构)获取所有事件,以及是否可以在数据库查询中这样做。

谢谢!

Django 查询集允许您使用“__”符号来访问关系。您可以深入了解它并阅读更多相关信息 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.

以下任何一项都适用于您的情况:

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)