--- /dev/null
+# -*- coding: utf-8 -*-
+# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
+# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
+#
+from __future__ import print_function, unicode_literals
+
+from django.core.management.base import BaseCommand
+from django.db.models import Count
+
+from catalogue.models import Book, BookPopularity
+
+
+class Command(BaseCommand):
+ help = 'Update popularity counters.'
+
+ def handle(self, **options):
+ BookPopularity.objects.all().delete()
+ books_with_popularity = Book.objects.filter(tag_relations__tag__category='set').only('id').distinct()\
+ .annotate(pop=Count('tag_relations__tag__user', distinct=True))
+ for book in books_with_popularity:
+ BookPopularity.objects.create(book=book, count=book.pop)
+ books_without_popularity = Book.objects.exclude(tag_relations__tag__category='set')
+ for book in books_without_popularity:
+ BookPopularity.objects.create(book=book, count=0)
--- /dev/null
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('catalogue', '0009_auto_20160127_1019'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='BookPopularity',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('count', models.IntegerField(default=0)),
+ ('book', models.OneToOneField(related_name='popularity', to='catalogue.Book')),
+ ],
+ ),
+ ]
from catalogue.models.tag import Tag
from catalogue.models.bookmedia import BookMedia
from catalogue.models.fragment import Fragment
-from catalogue.models.book import Book
+from catalogue.models.book import Book, BookPopularity
from catalogue.models.collection import Collection
from catalogue.models.source import Source
else:
return None
+ def update_popularity(self):
+ count = self.tags.filter(category='set').values('user').order_by('user').distinct().count()
+ try:
+ pop = self.popularity
+ pop.count = count
+ pop.save()
+ except BookPopularity.DoesNotExist:
+ BookPopularity.objects.create(book=self, count=count)
+
def add_file_fields():
for format_ in Book.formats:
).contribute_to_class(Book, field_name)
add_file_fields()
+
+
+class BookPopularity(models.Model):
+ book = models.OneToOneField(Book, related_name='popularity')
+ count = models.IntegerField(default=0)
# delete empty tags
Tag.objects.filter(category='set', user=user, items=None).delete()
+ if isinstance(work, Book):
+ work.update_popularity()
+
def cites_for_tags(tags):
"""Returns a QuerySet with all Cites for books with given tags."""