如何将此 SQL 查询传输到 Django orm 代码
How can I transfer this SQL query to Django orm code
模型(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
)
我们可以借助 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=<strong>Coalesce(Subquery(</strong>
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
)
模型(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
)
我们可以借助 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=<strong>Coalesce(Subquery(</strong>
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
)