-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0006_content_streamfield_data.py
More file actions
77 lines (66 loc) · 2.54 KB
/
0006_content_streamfield_data.py
File metadata and controls
77 lines (66 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Generated by Django 2.2.1 on 2019-05-03 13:18
import json
from uuid import uuid4
from copy import deepcopy
from django.core.serializers.json import DjangoJSONEncoder
from django.db import migrations
from wagtail.core.blocks import StreamValue
from home.models import ExamplePage
def copy_page_data_to_content_streamfield(apps, schema_editor):
"""With the given page, copy the page data to the content stream_data"""
for page in ExamplePage.objects.all():
page_data = json.loads(page.to_json())
content_data = page_data_to_content_streamfield_data(page_data)
if content_data != page.content.stream_data:
page.content.stream_data = content_data
page.save()
for revision in page.revisions.all():
revision_data = json.loads(revision.content_json)
content_data = page_data_to_content_streamfield_data(revision_data)
if content_data != revision_data.get('content'):
# StreamField data is stored in revision.content_json in a string field
revision_data['content'] = json.dumps(content_data)
revision.content_json = json.dumps(
revision_data, cls=DjangoJSONEncoder)
revision.save()
def prevent_reverse_migration(apps, schema_editor):
return
raise NotImplementedError(
"This migration cannot be reversed without" +
" inordinate expenditure of time. You can" +
" `--fake` it if you know what you're doing," +
" and are a migration ninja.", )
class Migration(migrations.Migration):
dependencies = [
('home', '0005_add_content_streamfield'),
]
operations = [
migrations.RunPython(
copy_page_data_to_content_streamfield,
prevent_reverse_migration,
)
]
def page_data_to_content_streamfield_data(page_data):
"""With the given page field data, build and return content stream_data:
* Copy existing page data into new stream_data.
* Handle either the main page data or any revision data.
* page_data is unchanged! (treated as immutable).
"""
content_data = [
{
'type': 'image',
'value': page_data['image']
},
{
'type': 'text',
'value': page_data['body']
},
{
'type':
'docs',
'value': [{key: block_data[key]
for key in ['type', 'value']}
for block_data in json.loads(page_data['docs'])]
},
]
return content_data