用 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

posted @ 2020-08-31 20:22  catgatp  阅读(1634)  评论(0编辑  收藏  举报