UserProxy's by_username_or_email() should raise DoesNotExist
[mygpo.git] / mygpo / suggestions / tasks.py
blobcbac6b432e5681521b0d068621f349467e5d8916
1 from itertools import chain
2 from collections import Counter
4 from mygpo.celery import celery
5 from mygpo.subscriptions import get_subscribed_podcasts
6 from mygpo.suggestions.models import PodcastSuggestion
8 from celery.utils.log import get_task_logger
9 logger = get_task_logger(__name__)
12 @celery.task
13 def update_suggestions(user, max_suggestions=15):
14 """ updates the suggestions of a user """
15 logger.info('Updating suggestions of user {user.username}'.format(
16 user=user))
18 # calculate possible suggestions
19 subscribed_podcasts = [sp.podcast for sp in get_subscribed_podcasts(user)]
20 logger.debug('Found {num_podcasts} subscribed podcasts'.format(
21 num_podcasts=len(subscribed_podcasts)))
23 # TODO: update related_podcasts of the subscribed_podcasts?
25 related = list(chain.from_iterable([p.related_podcasts.all() for p
26 in subscribed_podcasts]))
28 # get most relevant
29 counter = Counter(related)
30 logger.debug('Found {num_related} related podcasts'.format(
31 num_related=len(counter)))
33 suggested = [p for p, count in counter.most_common(max_suggestions)]
35 for suggested_podcast in suggested:
36 ps, created = PodcastSuggestion.objects.get_or_create(
37 suggested_to=user,
38 podcast=suggested_podcast,
40 if created:
41 logger.info('Created suggestion for {podcast}'.format(
42 podcast=suggested_podcast))
44 user.profile.suggestions_up_to_date = True
45 user.profile.save()