如何在sqlite django ORM中实现have子句 [英] How to implement the having clause in sqlite django ORM

查看:36
本文介绍了如何在sqlite django ORM中实现have子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于如何在sqlite django ORM中实现have子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆