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

相关文章:

  • 2021-06-22
  • 2022-01-30
  • 2021-06-19
  • 2022-12-23
  • 2021-10-04
  • 2021-05-31
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-24
  • 2022-12-23
  • 2022-01-12
  • 2021-10-12
  • 2022-01-15
  • 2022-12-23
相关资源
相似解决方案