Display fixes: shelf tags, search results.
[wolnelektury.git] / apps / catalogue / migrations / 0002_book_ancestor.py
1 # -*- coding: utf-8 -*-
2 from __future__ import unicode_literals
3
4 from django.db import models, migrations
5
6
7 def fix_tree_tags(apps, schema_editor):
8     """Fixes the ancestry cache."""
9     # TODO: table names
10     from django.db import connection, transaction
11     if connection.vendor == 'postgres':
12         cursor = connection.cursor()
13         cursor.execute("""
14             WITH RECURSIVE ancestry AS (
15                 SELECT book.id, book.parent_id
16                 FROM catalogue_book AS book
17                 WHERE book.parent_id IS NOT NULL
18                 UNION
19                 SELECT ancestor.id, book.parent_id
20                 FROM ancestry AS ancestor, catalogue_book AS book
21                 WHERE ancestor.parent_id = book.id
22                     AND book.parent_id IS NOT NULL
23                 )
24             INSERT INTO catalogue_book_ancestor
25                 (from_book_id, to_book_id)
26                 SELECT id, parent_id
27                 FROM ancestry
28                 ORDER BY id;
29             """)
30     else:
31         Book = apps.get_model("catalogue", "Book")
32         for b in Book.objects.exclude(parent=None):
33             parent = b.parent
34             while parent is not None:
35                 b.ancestor.add(parent)
36                 parent = parent.parent
37
38
39 def remove_book_tags(apps, schema_editor):
40     Tag = apps.get_model("catalogue", "Tag")
41     Book = apps.get_model("catalogue", "Book")
42     Tag.objects.filter(category='book').delete()
43
44
45 class Migration(migrations.Migration):
46
47     dependencies = [
48         ('catalogue', '0001_initial'),
49     ]
50
51     operations = [
52         migrations.AddField(
53             model_name='book',
54             name='ancestor',
55             field=models.ManyToManyField(related_name=b'descendant', null=True, editable=False, to='catalogue.Book', blank=True),
56             preserve_default=True,
57         ),
58
59         migrations.RunPython(fix_tree_tags),
60         migrations.RunPython(remove_book_tags),
61
62         migrations.AlterField(
63             model_name='tag',
64             name='category',
65             field=models.CharField(db_index=True, max_length=50, verbose_name='Category', choices=[(b'author', 'author'), (b'epoch', 'period'), (b'kind', 'form'), (b'genre', 'genre'), (b'theme', 'motif'), (b'set', 'set'), (b'thing', 'thing')]),
66         ),
67
68         migrations.RemoveField(
69             model_name='tag',
70             name='book_count',
71         ),
72         migrations.RemoveField(
73             model_name='tag',
74             name='picture_count',
75         ),
76         migrations.RemoveField(
77             model_name='book',
78             name='_related_info',
79         ),
80     ]