Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Returns some statistics when rating an object using ajax request #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ratings/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,10 @@ def unrate(self, user):
def perform_aggregation(self, aggregator):
score = self.all().aggregate(agg=aggregator('score'))
return score['agg']

def count(self):
# the number of votes
return self.perform_aggregation(models.Count)

def cumulative_score(self):
# simply the sum of all scores, useful for +1/-1
Expand Down
10 changes: 9 additions & 1 deletion ratings/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
HttpResponseNotAllowed, Http404
from django.shortcuts import get_object_or_404

import json

# allow GET requests to create ratings -- this goes against the "GET" requests
# should be idempotent but avoids the necessity of using <form> elements or
Expand Down Expand Up @@ -35,7 +36,14 @@ def rate_object(request, ct, pk, score=1, add=True):
ratings_descriptor.unrate(request.user)

if request.is_ajax():
return HttpResponse('{"success": true}', mimetype='application/json')
data = {"success": True,
"score": score,
"count": ratings_descriptor.count(),
"cumulative_score": ratings_descriptor.cumulative_score(),
"average_score": ratings_descriptor.average_score(),
}

return HttpResponse(json.dumps(data), content_type='application/json')
try:
return HttpResponseRedirect(request.REQUEST.get('next') or
request.META.get('HTTP_REFERER'))
Expand Down