如何在sqlite django ORM中实现have子句

2021-12-19 00:00:00 python django django-models orm sqlite

我已经编写了 django sqlite 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()

但它给了我一个错误,这个语法的 sql 对我来说很好.

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

这是我的 sql 等价物.

This is my sql equivalent.

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

我得到的结果如下

+----+--------+--------+---------+---------------------+---------+
| 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 |
+----+--------+--------+---------+---------------------+---------+

我无法为此找到等效的 django sqlite.

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

如果有人能提供帮助,我将不胜感激.

I will be very grateful if anyone can help.

推荐答案

我终于想通了.ORM 语法是这样的.

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

相关文章