Reputation:
Here's the model
class Answer(models.Model):
user = models.ForeignKey(User)
......
......
views = models.IntegerField(default=0)
How can I print the total number of views
for a specific user
for all the answers he/she have ever written?
Please help me, thanks in Advance!
Upvotes: 0
Views: 85
Reputation: 1454
You can use a query like:
from django.db.models import Sum
total_views = Answer.objects.get(user=user).aggregate(Sum('views'))
If you want to get a sum for a list of users, such as users with ids of [1, 5, 7, 12], you can do something like this:
from django.db.models import Sum
ids = [1, 5, 7, 12]
views_list = Answer.objects.filter(user__pk__in=ids).annotate(num_views = Sum('views'))
Then you would access each one by:
print(views_list[0].num_views)
Upvotes: 1