1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from django.core.management.base import BaseCommand
5 from django.db.models import Count
7 from catalogue.models import Book, BookPopularity
10 class Command(BaseCommand):
11 help = 'Update popularity counters.'
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))
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)