55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
import hashlib
|
|
import uuid
|
|
|
|
from django.db import migrations
|
|
|
|
|
|
def natural_key(page):
|
|
def get_parents_and_self(page):
|
|
pages = [page]
|
|
_page = page
|
|
while _page.parent_id:
|
|
_page = _page.parent
|
|
pages.append(_page)
|
|
return list(reversed(pages))
|
|
|
|
def get_online_url(page):
|
|
parts = [x.slug for x in get_parents_and_self(page)]
|
|
if parts[0] == 'index':
|
|
parts = parts[1:]
|
|
if not parts:
|
|
return '/'
|
|
return '/' + '/'.join(parts) + '/'
|
|
|
|
return get_online_url(page).strip('/')
|
|
|
|
|
|
def forward(apps, schema_editor):
|
|
Page = apps.get_model('data', 'Page')
|
|
known_uuids = set(Page.objects.filter(uuid__isnull=False).values_list('uuid', flat=True))
|
|
for page in Page.objects.filter(uuid__isnull=True):
|
|
if page.snapshot is not None:
|
|
page.uuid = uuid.uuid4()
|
|
page.save()
|
|
known_uuids.add(page.uuid)
|
|
continue
|
|
slug = natural_key(page) or 'index'
|
|
slug_hash = hashlib.sha256(slug.encode('utf-8'))
|
|
page.uuid = uuid.UUID(slug_hash.hexdigest()[:32])
|
|
if page.uuid in known_uuids:
|
|
# uuid unicity !
|
|
page.uuid = uuid.uuid4()
|
|
known_uuids.add(page.uuid)
|
|
page.save()
|
|
|
|
|
|
class Migration(migrations.Migration):
|
|
|
|
dependencies = [
|
|
('data', '0060_page_uuid'),
|
|
]
|
|
|
|
operations = [
|
|
migrations.RunPython(forward, reverse_code=migrations.RunPython.noop),
|
|
]
|