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]
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top