首页 > 解决方案 > 如何使用 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_moremy_model. 但是,与one_moreIS 相关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

我该怎么做呢?

标签: pythondjango

解决方案


如果要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存在关联的关联的Bars Quxyear例如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(..)查询相关模型。这些用于在相同(或其他查询)中获取相关模型,从而提高效率。当然,您也可以使用它们,但它们的用途与使相关模型可用于过滤不同。


推荐阅读