def record_vote self obj user vote Record user vote on given object On

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def record_vote(self, obj, user, vote):
"""
Record a user's vote on a given object. Only allows a given user
to vote once, though that vote may be changed.
A zero vote indicates that any existing vote should be removed.
"""
if vote not in (+1, 0, -1):
raise ValueError('Invalid vote (must be +1/0/-1)')
ctype = ContentType.objects.get_for_model(obj)
try:
v = self.get(user=user, content_type=ctype,
object_id=obj._get_pk_val())
if vote == 0:
v.delete()
else:
v.vote = vote
v.save()
except models.ObjectDoesNotExist:
if vote != 0:
self.create(user=user, content_type=ctype,
object_id=obj._get_pk_val(), vote=vote)