keep book popularity in model
[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         for book in books_with_popularity:
21             BookPopularity.objects.create(book=book, count=book.pop)
22         books_without_popularity = Book.objects.exclude(tag_relations__tag__category='set')
23         for book in books_without_popularity:
24             BookPopularity.objects.create(book=book, count=0)