[Django]-How to implement the having clause in sqlite django ORM

52👍

✅

Finally I’ve managed to figure it out. The ORM syntax is something like this.

from django.db.models.aggregates import Count

JobStatus.objects.filter(
    status='PRF'
).values_list(
    'job', flat=True
).order_by(
    'job'
).annotate(
    count_status=Count('status')
).filter(
    count_status__gt=1
).distinct()

12👍

More general rule for this: you need to create new column (by annotate) and then filter through that new column. This queryset will be transformed to HAVING keyword.

Leave a comment