【问题标题】:How can I transfer this SQL query to Django orm code如何将此 SQL 查询传输到 Django orm 代码
【发布时间】:2021-11-25 19:46:22
【问题描述】:

模型(pk/id是自动生成的)

class Comments(models.Model):
    parent = models.ForeignKey(to="self", null=True)

还有 SQL 查询

SELECT 
  *
FROM
  comments
WHERE
  (
    parent_id IN ( 1, 2, 3, 4 ) 
    AND
    ( SELECT COUNT(*) FROM comments AS f WHERE ( f.parent_id = comments.parent_id AND f.id <= comments.id ) )<= 2 
  )

【问题讨论】:

  • 你用的是什么 Django 版本?
  • django 2.0.7 和 mysql 5.6.48

标签: mysql django django-orm


【解决方案1】:

我们可以在Subquery 的帮助下确定计数:

from django.db.models import Count, OuterRef, Q, Subquery, Value
from django.db.models.functions import Coalesce

Comments.objects.filter(
    parent_id__in=[1,2,3,4]
).annotate(
    ncomment=Coalesce(Subquery(
        Comments.objects.filter(
            parent_id=OuterRef('pk'),
            pk__lte=OuterRef('pk')
        ).values('parent_id').annotate(
            ncomment=Count('pk')
        ).values('ncomment').order_by('parent_id')
    ), Value(0))
).filter(
    ncomment__lte=2
)

【讨论】:

  • 有效!真诚感谢您的回答
猜你喜欢
  • 2021-12-05
  • 2019-10-31
  • 2017-09-10
  • 2019-10-17
  • 2019-12-12
  • 1970-01-01
  • 2014-12-26
  • 2015-08-23
  • 2016-04-20
相关资源
最近更新 更多