extensions-website/ratings/signals.py

50 lines
1.4 KiB
Python

from statistics import median
from actstream import action
from django.db.models.signals import post_delete, post_save, pre_delete
from django.dispatch import receiver
from constants.activity import Verb
from ratings.models import Rating
from ratings.utils import compute_rating_sortkey
@receiver(post_delete, sender=Rating)
@receiver(post_save, sender=Rating)
def _update_rating_counters(sender, instance, *args, **kwargs):
extension = instance.extension
rating_values = extension.ratings.listed.values_list('score', flat=True)
if rating_values:
extension.average_score = median(rating_values)
extension.rating_sortkey = compute_rating_sortkey(rating_values)
else:
extension.average_score = 0
extension.rating_sortkey = 0
extension.save(update_fields={'average_score', 'rating_sortkey'})
@receiver(post_save, sender=Rating)
def _create_action_from_rating(
sender: object,
instance: Rating,
created: bool,
raw: bool,
**kwargs: object,
) -> None:
if raw:
return
if not created:
return
action.send(
instance.user,
verb=Verb.RATED_EXTENSION,
action_object=instance,
target=instance.extension,
)
@receiver(pre_delete, sender=Rating)
def _log_deletion(sender: object, instance: Rating, **kwargs: object) -> None:
instance.record_deletion()