annoying decorators py from django db models signals import post_save

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# annoying.decorators.py
from django.db.models.signals import post_save as _post_save
def post_save(sender):
def renderer(function):
def wrapper(sender, **kwargs):
_post_save.connect(function, sender=sender)
return function(sender, **kwargs)
return wrapper
return renderer
#signals.py
from annoying.decorators import post_save
@post_save(Vote)
def vote_recived(sender, **kwargs):
"""
count vote score of post and write it to post counter
"""
instance = kwargs['instance']
if isinstance(instance.object, Video):
video = instance.object
counter = [vote.vote for vote in video.votes.all()]
video.score = sum(counter)
video.save()
if isinstance(instance.object, Picture):
picture = instance.object
counter = [vote.vote for vote in picture.votes.all()]
picture.score = sum(counter)
picture.save()