23
votes

I've written django sqlite orm syntax to retrieve particular set of records:

from django.db.models.aggregates import Count

JobStatus.objects.filter(
    status='PRF'
).values_list(
    'job', flat=True
).order_by(
    'job'
).aggregate(
    Count(status)__gt=3
).distinct()

But it gives me an error and the sql equivalent for this syntax works fine for me.

This is my sql equivalent.

SELECT *
  FROM tracker_jobstatus
 WHERE status = 'PRF'
 GROUP BY job_id
HAVING COUNT(status) > 3;

and I'm getting the result as follows

+----+--------+--------+---------+---------------------+---------+
| id | job_id | status | comment | date_and_time       | user_id |
+----+--------+--------+---------+---------------------+---------+
| 13 |      3 | PRF    |         | 2012-11-12 13:16:00 |       1 |
| 31 |      4 | PRF    |         | 2012-11-12 13:48:00 |       1 |
+----+--------+--------+---------+---------------------+---------+

I'm unable to find the django sqlite equivalent for this.

I will be very grateful if anyone can help.

2
I asked about this in #django on Freenode some time ago and got the response that it wasn't possible. Sorry to be a bearer of bad news. - GlennS
not possible? if there is a proper tutorial we can figure it out in a what ever way . Thank you . - co2f2e
Glad to be proved wrong, thanks. - GlennS

2 Answers

44
votes

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()
9
votes

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.