Skip to content
Browse files

VoteManager.get_scores_in_bulk assumed it was working with a non-empt…

…y list

git-svn-id: https://django-voting.googlecode.com/svn/trunk@60 662f01ad-f42a-0410-a340-718c64ddaef4
  • Loading branch information...
1 parent ee0221e commit ede5eb5a29b0ff1cca2ceb4345f931f757c0ba5c @insin insin committed Nov 6, 2007
Showing with 24 additions and 19 deletions.
  1. +21 −18 voting/managers.py
  2. +3 −1 voting/tests/tests.py
View
39 voting/managers.py
@@ -31,24 +31,27 @@ def get_scores_in_bulk(self, objects):
Get a dictionary mapping object ids to total score and number
of votes for each object.
"""
- query = """
- SELECT object_id, SUM(vote), COUNT(vote)
- FROM %s
- WHERE content_type_id = %%s
- AND object_id IN (%s)
- GROUP BY object_id""" % (
- qn(self.model._meta.db_table),
- ','.join(['%s'] * len(objects))
- )
- ctype = ContentType.objects.get_for_model(objects[0])
- cursor = connection.cursor()
- cursor.execute(query, [ctype.id] + [obj._get_pk_val() \
- for obj in objects])
- results = cursor.fetchall()
- return dict([(int(object_id), {
- 'score': int(score),
- 'num_votes': int(num_votes),
- }) for object_id, score, num_votes in results])
+ vote_dict = {}
+ if len(objects) > 0:
+ query = """
+ SELECT object_id, SUM(vote), COUNT(vote)
+ FROM %s
+ WHERE content_type_id = %%s
+ AND object_id IN (%s)
+ GROUP BY object_id""" % (
+ qn(self.model._meta.db_table),
+ ','.join(['%s'] * len(objects))
+ )
+ ctype = ContentType.objects.get_for_model(objects[0])
+ cursor = connection.cursor()
+ cursor.execute(query, [ctype.id] + [obj._get_pk_val() \
+ for obj in objects])
+ results = cursor.fetchall()
+ vote_dict = dict([(int(object_id), {
+ 'score': int(score),
+ 'num_votes': int(num_votes),
+ }) for object_id, score, num_votes in results])
+ return vote_dict
def record_vote(self, obj, user, vote):
"""
View
4 voting/tests/tests.py
@@ -82,4 +82,6 @@
>>> Vote.objects.get_scores_in_bulk([i1, i2, i3, i4])
{1: {'score': 0, 'num_votes': 4}, 2: {'score': -2, 'num_votes': 4}, 3: {'score': -4, 'num_votes': 4}, 4: {'score': -3, 'num_votes': 3}}
-"""
+>>> Vote.objects.get_scores_in_bulk([])
+{}
+"""

0 comments on commit ede5eb5

Please sign in to comment.
Something went wrong with that request. Please try again.