How can I transfer this SQL query to Django orm code

The model(the pk/id is auto generated)

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

And the SQL query

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 
  )

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

We can determine the count with the help of a 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
)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x