1

I need to make this Query using Django QuerySystem.

SELECT  DATE(`date`), count(*)
FROM `maggie_item`
GROUP BY DATE(`date`) DESC

My model:

Item

  • date = DateTime
  • title = textfield

I would appreciate your help

2

2 Answers 2

3

Say your model is Item. Then:

from django.db.models import Count
Item.objects.values('date').annotate(Count('id'))

To group by dates instead of datetimes:

Item.objects.extra(select = { 'date': "DATE(date)" }).values('date').annotate(Count('id'))

I've only done this on Postgresql, where the following works, so I assume the above will work for you.

Item.objects.extra(select={'date' : "date_trunc('day', date)"}).values('date').annotate(Count('id'))
Sign up to request clarification or add additional context in comments.

1 Comment

This is almost correct but I need to group by DATE('date') (Dates instead of datetimes). For example: Item.objects.values('date').annotate(Count('id')).order_by('date_date')
0

I did not find anyway to cast and group on using Django Query System, So I use a cursor

from django.db import connection

cursor = connection.cursor()
cursor.execute("SELECT DATE(date), count(id) FROM maggie_item GROUP BY DATE(date) DESC")
for a in cursor:
    print a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.