【问题标题】:Select Related With Multiple Conditions选择与多个条件相关
【发布时间】:2020-08-27 03:13:51
【问题描述】:

使用 Django ORM 可以在默认 table1.id = table2.fk 之外的条件下执行 select_related(左连接)

使用示例模型:

class Author(models.Model):
    name = models.TextField()
    age = models.IntegerField()

class Book(models.Model):
    title = models.TextField()

和原始的 sql

SELECT 'Book'.*, 'Author'.'name' FROM 'Book' LEFT JOIN 'Author' ON 'Author'.'id' = 'Book'.'author_id' AND 'Author'.'age' > 18 ;<---this line here is what id like to use via the ORM

我知道在这个简单的示例中,您可以在加入后执行过滤,但这在我的具体情况下不起作用。因为我正在对需要过滤器的多个左连接进行求和。

【问题讨论】:

  • 您能否更新相关模型并指定您的实际要求。或许那时我们可以找到解决此问题的方法。

标签: sql django django-models orm


【解决方案1】:
# gets all books which has author with age higher than 18
books = Book.objects.filter(author__age__gt=18) 

返回查询集。

然后您可以循环通过查询集来访问特定值并打印它们:

for b in books:
    print(b.title, b.author.name, b.author.age)

【讨论】:

  • 该问题专门要求基于连接进行过滤,而不是像您的示例中那样在 WHERE 子句中进行过滤
猜你喜欢
  • 1970-01-01
  • 2014-02-12
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
相关资源
最近更新 更多