Commits

Kai Diefenbach committed 35debd2

Added ``get_best_rated`` and ``get_best_rated_for_model`` methods.

Comments (0)

Files changed (1)

 # review imports
 from reviews.models import Review
 
+def get_best_rated():
+    """Returns the best rated instance at all.
+    """
+    cursor = connection.cursor()
+    cursor.execute("""SELECT avg(score), content_type_id, content_id
+                      FROM reviews_review
+                      WHERE active=%s
+                      GROUP BY content_id
+                      ORDER BY score DESC""", [True])
+
+    try:
+        score, content_type_id, content_id = cursor.fetchone()
+        ctype = ContentType.objects.get_for_id(content_type_id)
+        content = ctype.model_class().objects.get(pk=content_id)
+        return content, score
+    except (TypeError, ObjectDoesNotExist):
+        return None
+
+def get_best_rated_for_model(instance):
+    """Returns the best rated instance for given model or instance of a model.
+    """
+    ctype = ContentType.objects.get_for_model(instance)
+
+    cursor = connection.cursor()
+    cursor.execute("""SELECT avg(score), content_id
+                      FROM reviews_review
+                      WHERE content_type_id=%s
+                      AND active=%s
+                      GROUP BY content_id
+                      ORDER BY score DESC""", [ctype.id, True])
+
+    try:
+        score, content_id = cursor.fetchone()
+        content = ctype.model_class().objects.get(pk=content_id)
+        return content, score
+    except (TypeError, ObjectDoesNotExist):
+        return None
+
 def get_reviews_for_instance(instance):
     """Returns active reviews for given instance.
     """
 def get_average_for_instance(instance):
     """Returns the average score and the amount of reviews for the given
     instance. Takes only active reviews into account.
-    
+
     Returns (average, amount)
     """
     # TODO: Check Django 1.1's aggregation