用 django orm 寫 exists 條件過濾


要用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM