python - 如何使用 django 的 ORM 进行两个连接
问题描述
我正在使用 django ORM 进行如下查询:
MyModel.objects.filter(<condition>)
这就是这样的查询:
SELECT my_model.* FROM my_model WHERE <condition>
如果我想加入另一张桌子,我可以这样做:
MyModel.objects.select_related('other_table').filter(<condition>)
结果是:
SELECT my_model.*, other_table.* FROM my_model
JOIN other_table ON my_model.other_table_id = other_table.id
如果我需要进行两次连接,我该怎么办?
如果我做类似的事情MyModel.objects.select_related('other_table', 'one_mode').filter(<condition>)
我收到一个错误,说one_more
与my_model
. 但是,与one_more
IS 相关other_table
,ORM 没有检测到。
基本上我正在尝试这样做:
SELECT my_model.*, other_table.* FROM my_model
JOIN other_table ON my_model.other_table_id = other_table.id
JOIN one_more ON one_mode.id = other_table.one_mode_id
我该怎么做呢?
解决方案
如果要JOIN
在相关模型上使用,请使用双下划线( __
)。因此,如果您的模型是例如:
class Foo(models.Model):
pass
class Bar(models.Model):
foo = models.ForeignKey(Foo, on_delete=models.CASCADE)
class Qux(models.Model):
bar = models.ForeignKey(Foo, on_delete=models.CASCADE)
year = models.IntegerField()
您可以获得所有Foo
存在关联的关联的Bar
s Qux
,year
例如2019
:
Foo.objects.filter(bar__qux__year=2019)
这将导致如下查询:
SELECT foo.*
FROM foo
JOIN bar ON bar.foo_id = foo.id
JOIN qux ON qux.bar_id = bar.id
WHERE qux.year = 2019
请注意,无需使用.select_related(..)
或.prefetch_related(..)
查询相关模型。这些用于在相同(或其他查询)中获取相关模型,从而提高效率。当然,您也可以使用它们,但它们的用途与使相关模型可用于过滤不同。
推荐阅读
- c++ - 带有单独头的类:只能看到成员变量的初始化值
- android - 使用 android Selector XML 文件时出错 - 没有 android:color="xxx" 的有效属性,用标签内的项目替换
- sql-server - 检查数据库中是否已经存在数据
- powershell - 在powershell中运行exe并在取消时返回代码
- javascript - gitlab 上的 CI/CD 无法使用 babel-loader 编译
- angularjs - 引导表单验证在 AngularJS 中不起作用
- laravel - 如何手动将用户详细信息设置为 Auth::User() 详细信息
- html - 如何在 play framework 2.6 中使用 hhandoko (play26-scala-pdf) 动态添加 pdf 页眉和页脚
- sql - 依靠 GROUP BY 以及结果总数
- java - 如何获取json数组数据并在SPINNERS android中显示