Fakhir
Fakhir

Reputation: 78

How i can use aggregation in django

I want aggregate result using Django ORM. Sample table structure is:

sample_table

| **id | user_id | viewed | likes |     abc**    |

|  1   | 123     |    1   |   1   |   0.1258965  |

|  2   | 222     |    0   |   1   |   0.0004585  |

|  3   | 123     |    0   |   0   |   0.0025802  |

|  4   | 123     |    1   |   1   |   0.2500245  |

I need results according to user_id e.g

[user_id, total viewd, total likes, total abc]

Upvotes: 2

Views: 59

Answers (1)

Bogdan Iulian Bursuc
Bogdan Iulian Bursuc

Reputation: 2275

Since you want the values grouped per user, you will have to filter on the User model and annotate each row to include the aggregations.

Assuming that sample_table has the model Sample and a foreign key to User you can do this:

from django.db.models import Sum

User.objects.annotate(total_viewed=Sum('sample__viewed'), 
                      total_likes=Sum('sample__likes'),
                      total_abc=Sum('sample__abc'))

And each user row will also have the fields total_viewed, total_likes and total_abc.

Upvotes: 3

Related Questions