fix
[redakcja.git] / src / depot / migrations / 0010_migrate_external_ids.py
1 # Generated by Django 4.1.9 on 2023-09-05 14:14
2
3 from django.db import migrations
4
5
6 def migrate_external_ids(apps, schema_editor):
7     Book = apps.get_model('documents', 'Book')
8     Site = apps.get_model('depot', 'Site')
9     SiteBook = apps.get_model('depot', 'SiteBook')
10     SiteBookPublish = apps.get_model('depot', 'SiteBookPublish')
11
12     site_types = ('legimi', 'woblink')
13     for site_type in site_types:
14         site = Site.objects.filter(site_type=site_type).first()
15         if site is None:
16             continue
17         for book in Book.objects.exclude(**{f'{site_type}_id': ''}):
18             SiteBook.objects.get_or_create(
19                 site=site, book=book,
20                 external_id=getattr(book, f'{site_type}_id')
21             )
22
23     for p in SiteBookPublish.objects.all():
24         p.site_book, created = SiteBook.objects.get_or_create(
25             site=p.site,
26             book=p.book
27         )
28         p.save(update_fields=['site_book'])
29             
30     
31
32 def remigrate_external_ids(apps, schema_editor):
33     Book = apps.get_model('documents', 'Book')
34     Site = apps.get_model('depot', 'Site')
35     SiteBook = apps.get_model('depot', 'SiteBook')
36     SiteBookPublish = apps.get_model('depot', 'SiteBookPublish')
37
38     for p in SiteBookPublish.objects.exclude(site_book=None):
39         p.site = p.site_book.site
40         p.book = p.site_book.book
41         p.save(update_fields=['site', 'book'])
42
43     site_types = ('legimi', 'woblink')
44     for site_type in site_types:
45         for site_book in SiteBook.objects.exclude(external_id=None):
46             book = site_book.book
47             setattr(book, f'{site_type}_id', site_book.external_id)
48             book.save(update_fields=[f'{site_type}_id'])
49     
50
51 class Migration(migrations.Migration):
52
53     dependencies = [
54         ("depot", "0009_sitebook_sitebookpublish_site_book"),
55     ]
56
57     operations = [
58         migrations.RunPython(
59             migrate_external_ids,
60             remigrate_external_ids,
61         )
62     ]