Возникла задача раскидать файлы, загруженные пользователями по разным каталогам:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.conf import settings
from django.db import migrations
u""" Миграция выполняет перемещение файлов, привязанных к заказам, в
новое место на файловой системе."""
OLD_PATH = 'orders'
def upload_by_user_email(instance, filename):
"""Формируем путь для сохранения файлов."""
return u'orders/%s/%s' % (instance.customer.email, filename)
def migrate(app_registry, schema_editor):
PrintRequest = app_registry.get_model('order', 'PrintRequest')
for order in PrintRequest.objects.all():
relative_file_path_current = order.model.name
full_file_path_current = os.path.join(settings.MEDIA_ROOT, relative_file_path_current)
file_name = os.path.basename(full_file_path_current)
relative_file_path_target = upload_by_user_email(order, file_name)
full_file_path_target = os.path.join(settings.MEDIA_ROOT, relative_file_path_target)
full_dir_path_target = os.path.dirname(full_file_path_target)
if relative_file_path_current != relative_file_path_target:
if not os.path.exists(full_dir_path_target):
os.makedirs(full_dir_path_target)
os.rename(full_file_path_current, full_file_path_target)
order.model.name = relative_file_path_target
order.save()
class Migration(migrations.Migration):
dependencies = [
('order', '0007_user_link'),
]
operations = [
migrations.RunPython(migrate, migrations.RunPython.noop),
]