0

In am trying to reproduce the following plain SQL query using Django's ORM :

SELECT date, COUNT(*) FROM main_like GROUP BY date;

How can i do this request from Django ?

Stéphane Millien
  • 3,238
  • 22
  • 36

1 Answers1

0

In Django, people would usually do :

from my_app.models import main_like
from django.db.models import Count

result = (main_like.objects
    .values('date')
    .annotate(dcount=Count('date'))
    .order_by()
)

This would create the following query :

SELECT date, COUNT(date) AS dcount
FROM main_like GROUP BY date

Output would be like :

[{'date': 'date1', 'dcount': 2}, 
 {'date': 'date2', 'dcount': 2}]

The answer is inspired from this previous issue : How to query as GROUP BY in django?

AlexTorx
  • 753
  • 4
  • 9