使用django获取对象的孙子 [英] Get grandchildren of an object with django

查看:84
本文介绍了使用django获取对象的孙子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django构建具有以下模型的Web应用程序:

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.

谢谢!

推荐答案

Django查询集允许您使用 __表示法来访问关系。您可以深入了解它并进一步了解它此处

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提供了一种强大而直观的方式来跟踪查找中的关系
,在
背后自动为您处理SQL JOIN。要扩展关系,只需在各个模型中使用相关
字段的字段名称,并用双下划线将其分隔,直到获得所需的字段

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)

这篇关于使用django获取对象的孙子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆