def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ratings = get_anonymous_ratings(self.request.session) works = ( Work.objects.filter(id__in=ratings) .order_by('title') .group_by_category() ) categories = Category.objects.filter(id__in=works).in_bulk() # Build the tree of ratings. This is a list of pairs (category, works) # where category is a Category object and works is the list of ratings # for objects of this category. works itself is a list of dictionnaries # {'work', 'choice'} where the 'work' key corresponds to the Work # object that was rated and 'choice' corresponds to the rating. # # Example: # [ # (anime_category, [{'choice': 'like', 'work': Work()}, {'choice': 'dislike', 'work': Work()}]), # (manga_ategory, [{'choice': 'like', 'work': Work()}]) # ] context['ratings'] = [ (categories[category_id], [ {'choice': ratings[work.id], 'work': work} for work in works_list ]) for category_id, works_list in works.items() ] return context
def signup(self, request, user): if self.cleaned_data['import_ratings']: ratings = get_anonymous_ratings(request.session) clear_anonymous_ratings(request.session) Rating.objects.bulk_create([ Rating(user=user, work_id=work_id, choice=choice) for work_id, choice in ratings.items() ])
def signup(self, request, user): if self.cleaned_data['import_ratings']: ratings = get_anonymous_ratings(request.session) clear_anonymous_ratings(request.session) Rating.objects.bulk_create([ Rating(user=user, work_id=work_id, choice=choice) for work_id, choice in ratings.items() ]) Profile.objects.filter(id=user.profile.pk).update( newsletter_ok=self.cleaned_data['newsletter_ok'], research_ok=self.cleaned_data['research_ok'])
def get_profile_ratings(request, category: str, already_seen: bool, can_see: bool, is_anonymous: bool, user: User) -> Tuple[List[Rating], Counter]: counts = Counter() if is_anonymous: ratings = [] anon_ratings = get_anonymous_ratings(request.session) works_per_pk = Work.objects.select_related('category').in_bulk(anon_ratings.keys()) for pk, choice in anon_ratings.items(): rating = Rating() rating.work = works_per_pk[pk] rating.choice = choice seen_work = rating.choice not in SEE_CHOICES['unseen'] count_key = 'seen_{}' if seen_work else 'unseen_{}' counts[count_key.format(rating.work.category.slug)] += 1 if already_seen == seen_work and rating.work.category.slug == category: ratings.append(rating) elif can_see: ratings = list( Rating.objects .filter(user=user, work__category__slug=category, choice__in=SEE_CHOICES['seen'] if already_seen else SEE_CHOICES['unseen']) .select_related('work', 'work__category') ) categories = Category.objects.all() for category in categories: qs = Rating.objects.filter(user=user, work__category=category) seen = qs.filter(choice__in=SEE_CHOICES['seen']).count() unseen = qs.count() - seen counts['seen_{}'.format(category.slug)] = seen counts['unseen_{}'.format(category.slug)] = unseen else: ratings = [] return ratings, counts