newsletter stub
[wolnelektury.git] / src / catalogue / management / commands / update_popularity.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from __future__ import print_function, unicode_literals
6
7 from django.core.management.base import BaseCommand
8 from django.db.models import Count
9
10 from catalogue.models import Book, BookPopularity
11
12
13 class Command(BaseCommand):
14     help = 'Update popularity counters.'
15
16     def handle(self, **options):
17         BookPopularity.objects.all().delete()
18         books_with_popularity = Book.objects.filter(tag_relations__tag__category='set').only('id').distinct()\
19             .annotate(pop=Count('tag_relations__tag__user', distinct=True))
20         pop_list = []
21         for book in books_with_popularity:
22             pop_list.append(BookPopularity(book=book, count=book.pop))
23         books_without_popularity = Book.objects.exclude(tag_relations__tag__category='set')
24         for book in books_without_popularity:
25             pop_list.append(BookPopularity(book=book, count=0))
26         BookPopularity.objects.bulk_create(pop_list, batch_size=512)