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

2023-10-08数据库问题
2

本文介绍了如何在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子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

sql group by 与不同
sql group by versus distinct(sql group by 与不同)...
2024-04-16 数据库问题
37

Django MySQLdb 版本与 _mysql 版本 Ubuntu 不匹配
Django MySQLdb version doesn#39;t match _mysql version Ubuntu(Django MySQLdb 版本与 _mysql 版本 Ubuntu 不匹配)...
2024-04-16 数据库问题
11

将 MySQL EAV 结果作为关系表检索的最佳性能是什么
What is best performance for Retrieving MySQL EAV results as Relational Table(将 MySQL EAV 结果作为关系表检索的最佳性能是什么)...
2024-04-16 数据库问题
2

如何使用Python+SQLAlchemy远程连接MySQL数据库?
How to connect MySQL database using Python+SQLAlchemy remotely?(如何使用Python+SQLAlchemy远程连接MySQL数据库?)...
2024-04-16 数据库问题
15

是否可以执行按位分组功能?
Is it possible to perform a bitwise group function?(是否可以执行按位分组功能?)...
2024-04-16 数据库问题
7

当 Distinct 和 Group By 的表现不同时?
When the performance of Distinct and Group By are different?(当 Distinct 和 Group By 的表现不同时?)...
2024-04-16 数据库问题
7