Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement the having clause in sqlite django ORM

Tags:

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.

like image 651
Gayan Kalanamith Avatar asked Nov 12 '12 13:11

Gayan Kalanamith


People also ask

Does Django have ORM?

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL.

What is __ in Django ORM?

In Django, above argument is called field lookups argument, the field lookups argument's format should be fieldname__lookuptype=value. Please note the double underscore ( __ ) between the field name(depe_desc) and lookup type keyword contains.

What is Django ORM and its benefits over raw SQL?

The Django ORM provides many tools to express queries without writing raw SQL. For example: The QuerySet API is extensive. You can annotate and aggregate using many built-in database functions. Beyond those, you can create custom query expressions.


2 Answers

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() 
like image 165
Gayan Kalanamith Avatar answered Nov 01 '22 12:11

Gayan Kalanamith


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.

like image 41
Melevir Avatar answered Nov 01 '22 11:11

Melevir