Skip to content

Commit

Permalink
VoteManager.get_scores_in_bulk assumed it was working with a non-empt…
Browse files Browse the repository at this point in the history
…y list

git-svn-id: https://django-voting.googlecode.com/svn/trunk@60 662f01ad-f42a-0410-a340-718c64ddaef4
  • Loading branch information
insin committed Nov 6, 2007
1 parent ee0221e commit ede5eb5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 19 deletions.
39 changes: 21 additions & 18 deletions voting/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
4 changes: 3 additions & 1 deletion voting/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.