From 2550c52a61ef652d2da2a2c9ab564924df1b6c91 Mon Sep 17 00:00:00 2001 From: "Edgar P. Burkhart" Date: Sat, 31 Dec 2022 17:57:54 +0100 Subject: [PATCH] Add file migration --- .../migrations/0023_auto_20221231_1741.py | 63 +++++++++++++++++++ nummi/main/models.py | 2 +- 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 nummi/main/migrations/0023_auto_20221231_1741.py diff --git a/nummi/main/migrations/0023_auto_20221231_1741.py b/nummi/main/migrations/0023_auto_20221231_1741.py new file mode 100644 index 0000000..602949d --- /dev/null +++ b/nummi/main/migrations/0023_auto_20221231_1741.py @@ -0,0 +1,63 @@ +# Generated by Django 4.1.4 on 2022-12-31 16:41 + +import pathlib + +from django.conf import settings +from django.db import migrations + +import main.models + + +def move_files(apps, schema_editor): + Invoice = apps.get_model("main", "Invoice") + Snapshot = apps.get_model("main", "Snapshot") + + for invoice in Invoice.objects.all(): + print(invoice.pk) + if invoice.file is None: + invoice.delete() + continue + try: + initial_path = pathlib.Path(invoice.file.path) + except ValueError: + invoice.delete() + continue + if invoice.file is None or not initial_path.exists(): + print(f"!!! Path {initial_path} does not exist") + invoice.delete() + continue + _name = main.models.get_path(invoice, None) + new_path = pathlib.Path(settings.MEDIA_ROOT, _name) + new_path.parent.mkdir(mode=0o750, parents=True, exist_ok=True) + initial_path.rename(new_path) + invoice.file.name = str(_name) + invoice.save() + + for snapshot in Snapshot.objects.filter(file__isnull=False): + print(snapshot.pk) + try: + initial_path = pathlib.Path(snapshot.file.path) + except ValueError: + snapshot.file = None + snapshot.save() + continue + if not initial_path.exists(): + print(f"!!! Path {initial_path} does not exist") + snapshot.file = None + snapshot.save() + continue + _name = main.models.get_path(snapshot, None) + new_path = pathlib.Path(settings.MEDIA_ROOT, _name) + new_path.parent.mkdir(mode=0o750, parents=True, exist_ok=True) + initial_path.rename(new_path) + snapshot.file.name = str(_name) + snapshot.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ("main", "0022_alter_account_icon_alter_category_icon"), + ] + + operations = [migrations.RunPython(move_files)] diff --git a/nummi/main/models.py b/nummi/main/models.py index 5a32d8b..2492404 100644 --- a/nummi/main/models.py +++ b/nummi/main/models.py @@ -34,7 +34,7 @@ class CustomModel(UserModel): def get_path(instance, filename): return pathlib.Path( "user", - str(instance.user.get_username()), + str(instance.user.username), instance._meta.model_name, str(instance.pk), ).with_suffix(".pdf")