Convert working SQL to Django ORM - SUM aggregate based on two fields -


i'm trying convert working sql query django orm statement.

for every location want retrieve popular date based on sum of activities 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) core_raw, core_location core_location.id = core_raw.location_id group date, slug order slug, sum desc; 

result:

    date    |   slug    | sum   ------------+-----------+------  2015-07-01 | berlin    | 1246  2015-07-02 | london    |  285  2015-07-02 | melbourne |  123 

how can django orm? possible?!

this can help.

from django.db.models import sum  values = raw.objects.all().values('location_slug','date').annotate(data_sum=sum('activities')).distinct() 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -