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.db import migrations
7 def populate_ancestors(apps, schema_editor):
8 """Fixes the ancestry cache."""
10 from django.db import connection, transaction
11 if connection.vendor == 'postgres':
12 cursor = connection.cursor()
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
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
24 INSERT INTO catalogue_book_ancestor
25 (from_book_id, to_book_id)
31 Book = apps.get_model("catalogue", "Book")
32 for book in Book.objects.exclude(parent=None):
34 while parent is not None:
35 book.ancestor.add(parent)
36 parent = parent.parent
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()
45 class Migration(migrations.Migration):
48 ('catalogue', '0002_book_ancestor'),
52 migrations.RunPython(populate_ancestors),
53 migrations.RunPython(remove_book_tags),