remove unnecessary imports
[mygpo.git] / mygpo / data / management / commands / update-suggestions.py
blob8a13b41362fe25d5ab452c9aaea75038241ba084
1 from django.core.management.base import BaseCommand
2 from django.contrib.auth.models import User
3 from optparse import make_option
4 from mygpo.api.models import SuggestionEntry, Subscription, UserProfile
5 from mygpo.data.models import RelatedPodcast, SuggestionBlacklist
7 class Command(BaseCommand):
9 option_list = BaseCommand.option_list + (
10 make_option('--max', action='store', type='int', dest='max', default=15, help="Maximum number of suggested podcasts per user."),
11 make_option('--outdated-only', action='store_true', dest='outdated', default=False, help="Update only users where the suggestions are not up-to-date"),
12 make_option('--user', action='store', type='string', dest='username', default='', help="Update a specific user"),
15 def handle(self, *args, **options):
17 max = options.get('max')
19 users = User.objects.filter(is_active=True)
21 if options.get('outdated'):
22 users = users.filter(userprofile__suggestion_up_to_date=False)
24 if options.get('username'):
25 users = users.filter(username=options.get('username'))
27 for user in users:
28 subscribed_podcasts = set([s.podcast for s in Subscription.objects.filter(user=user)])
29 related = RelatedPodcast.objects.filter(ref_podcast__in=subscribed_podcasts).exclude(rel_podcast__in=subscribed_podcasts)
30 related_podcasts = {}
31 for r in related:
33 # remove potential suggestions that are in the same group as already subscribed podcasts
34 if r.rel_podcast.group and Subscription.objects.filter(podcast__group=r.rel_podcast.group).exists():
35 continue
37 # don't suggest blacklisted podcasts
38 if SuggestionBlacklist.objects.filter(user=user, podcast=r.rel_podcast).exists():
39 continue
41 related_podcasts[r.rel_podcast] = related_podcasts.get(r.rel_podcast, 0) + r.priority
44 podcast_list = [(p, podcast) for (p, podcast) in related_podcasts.iteritems()]
45 podcast_list.sort(key=lambda (p, priority): priority, reverse=True)
47 SuggestionEntry.objects.filter(user=user).delete()
48 for (p, priority) in podcast_list[:max]:
49 SuggestionEntry.objects.create(podcast=p, priority=priority, user=user)
51 # flag suggestions up-to-date
52 p, _created = UserProfile.objects.get_or_create(user=user)
53 p.suggestion_up_to_date = True
54 p.save()