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

时间:2022-06-01 18:46:46

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

我编写了django sqlite orm语法来检索特定的记录集:

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.

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

This is my sql equivalent.

这是我的sql等价物。

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.

我无法找到与此相关的django sqlite。

I will be very grateful if anyone can help.

如果有人能提供帮助,我将非常感激。

2 个解决方案

#1


34  

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

最后我设法弄明白了。 ORM语法是这样的。

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

#2


7  

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.

更通用的规则:您需要创建新列(通过注释),然后筛选该新列。此查询集将转换为HAVING关键字。

#1


34  

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

最后我设法弄明白了。 ORM语法是这样的。

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

#2


7  

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.

更通用的规则:您需要创建新列(通过注释),然后筛选该新列。此查询集将转换为HAVING关键字。