Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

python - How to implement the having clause in sqlite django ORM

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...