annotate in django code example
Example 1: django group by
from django.db.models import Count
Members.objects.values('designation').annotate(dcount=Count('designation'))
SELECT designation, COUNT(designation) AS dcount
FROM members GROUP BY designation
[{'designation': 'Salesman', 'dcount': 2},
{'designation': 'Manager', 'dcount': 2}]
Example 2: sum values in django models and insert value in model field
def total_amount_spent(self):
temp_values = [int(user.amount_spent) for user in ExtendedProfile.objects.all()]
return sum(temp_values)