要用django的orm表達sql的exists子查詢,需要做兩部來完成
from django.db.models import Exists, OuterRef # 1. 定義子查詢條件 relative_comments = Comment.objects.filter( post=OuterRef('pk'), # 注意外鍵關聯方式:post為Comment表的字段,pk表示關聯另一表主鍵 ) # 2. 使用annotate和filter共同定義子查詢 Post.objects.annotate( # 使用exists定義一個額外字段 recent_comment=Exists(recent_comments), ).filter(recent_comment=True) # 在條件中通過檢查額外字段實現exists子查詢過濾
官網參考: https://docs.djangoproject.com/en/2.1/ref/models/expressions/#filtering-on-a-subquery-expression