I'm trying to convert a working SQL query to a Django ORM statement.
For every location I want to retrieve the most popular date based on the sum of all activities for each date+location.
Django models:
class Location(models.Model):
slug = models.SlugField(unique=True)
class Raw(models.Model):
location = models.ForeignKey('Location', related_name='raw')
activities = models.PositiveIntegerField(db_index=True)
date = models.DateField(db_index=True)
Data set:
date | activities | location_slug
------------+------------+-----------
2015-07-02 | 234 | london
2015-07-07 | 100 | london
2015-07-02 | 51 | london
2015-07-02 | 12 | melbourne
2015-07-02 | 111 | melbourne
2015-07-01 | 1234 | berlin
2015-07-01 | 12 | berlin
Working SQL.
SELECT DISTINCT ON (slug) date, slug, SUM(activities)
FROM core_raw, core_location
WHERE core_location.id = core_raw.location_id
GROUP BY date, slug
ORDER BY slug, sum DESC;
Result:
date | slug | sum
------------+-----------+------
2015-07-01 | berlin | 1246
2015-07-02 | london | 285
2015-07-02 | melbourne | 123
How can I do this with the Django ORM? Is it even possible?!