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