From 3a2fd2982ec1cfd16979dcd2c018a6c676a455d3 Mon Sep 17 00:00:00 2001 From: Nicolas ELIE Date: Sat, 8 Feb 2014 18:53:27 +0100 Subject: [PATCH] Returns some statistics when rating an object using ajax request --- ratings/models.py | 4 ++++ ratings/views.py | 10 +++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/ratings/models.py b/ratings/models.py index 7d95d5c..87bfcb4 100644 --- a/ratings/models.py +++ b/ratings/models.py @@ -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 diff --git a/ratings/views.py b/ratings/views.py index cb99cab..4707508 100644 --- a/ratings/views.py +++ b/ratings/views.py @@ -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
elements or @@ -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'))