Add file migration
This commit is contained in:
parent
06704aaa77
commit
02e599ca54
2 changed files with 51 additions and 1 deletions
50
nummi/main/migrations/0023_auto_20221231_1741.py
Normal file
50
nummi/main/migrations/0023_auto_20221231_1741.py
Normal file
|
@ -0,0 +1,50 @@
|
|||
# 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")
|
||||
db_alias = schema_editor.connection.alias
|
||||
|
||||
for invoice in Invoice.objects.using(db_alias).all():
|
||||
initial_path = pathlib.Path(invoice.file.path)
|
||||
if not initial_path.exists():
|
||||
invoice.file = None
|
||||
invoice.save()
|
||||
return
|
||||
_name = main.models.get_path(invoice, None)
|
||||
print(settings.MEDIA_ROOT)
|
||||
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 = _name
|
||||
invoice.save()
|
||||
|
||||
for snapshot in Snapshot.objects.using(db_alias).filter(file__isnull=False):
|
||||
initial_path = pathlib.Path(snapshot.file.path)
|
||||
if not initial_path.exists():
|
||||
invoice.file = None
|
||||
invoice.save()
|
||||
return
|
||||
_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 = _name
|
||||
snapshot.save()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("main", "0022_alter_account_icon_alter_category_icon"),
|
||||
]
|
||||
|
||||
operations = [migrations.RunPython(move_files)]
|
|
@ -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")
|
||||
|
|
Loading…
Reference in a new issue