1 # -*- coding: utf-8 -*-
2 from __future__ import unicode_literals
4 from django.db import models, migrations
7 def fix_tree_tags(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 b in Book.objects.exclude(parent=None):
34 while parent is not None:
35 b.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', '0001_initial'),
55 field=models.ManyToManyField(related_name=b'descendant', null=True, editable=False, to='catalogue.Book', blank=True),
56 preserve_default=True,
59 migrations.RunPython(fix_tree_tags),
60 migrations.RunPython(remove_book_tags),
62 migrations.AlterField(
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')]),
68 migrations.RemoveField(
72 migrations.RemoveField(
76 migrations.RemoveField(