如何在 django 中用 orm 寫子查詢

kingron發表於2024-06-21

如果想實現下面的 SQL:

SELECT * FROM book WHERE author_id IN (SELECT id FROM author WHERE name LIKE 'kingron%')

可以這樣寫:

authores = Author.objects.filter(name__startswith='kingron')

# 預設使用 pk 作為查詢的列
books = Book.objects.filter(author_id__in=authores)

也可以透過 values 指定子查詢的列

authores = authores.values('name')
books = Book.objects.filter(author_name__in=authores)

對應的 SQL 類似於:

SELECT * FROM book WHERE author_name IN (SELECT name FROM author WHERE name LIKE 'kingron%')

相關文章