Shubham
Shubham

Reputation: 531

MYSQL equivalent query in Django Average and Group By

Please help me to write the same query in Django using ORM

SELECT DATE(`created_at`) DateOnly, 
AVG(`amout`) AS val_1  
FROM `account`  
GROUP BY DateOnly

Upvotes: 0

Views: 80

Answers (1)

minglyu
minglyu

Reputation: 3337

Cast the datetime to date using Cast and then aggregate using values. A common idiom in ORM .values().annotate(..) is used to perform group by operation.

from django.db.models.functions import Cast
from django.db.models import DateField

Account.objects.annotate(
   DateOnly = Cast('created_at', output_field=DateField()),
).values('DateOnly').annotate(val_1 = Avg('amout'))

Upvotes: 1

Related Questions