2

Some additional features were added to a django application, and as a result the upload_to function also expanded.

Since django by default stores filenames in the database, and files on disk, no harm has been done - new files are named using a new upload_to function, while old files continue to work.

However, this is messy - we end up in a situation with files like

/media/userID/oldfilename.pdf 

and

/media/app/userID/projectID/newfilename.pdf 

Is there a way to bulk rename those files? I guess it could be done by iterating through the database, checking if the path in FileField matches the result of current upload_to, and if not, rename.. it seems like a common problem, so perhaps there is a more generic way out there?

qdot
  • 6,195
  • 5
  • 44
  • 95

1 Answers1

1

The simple solution is to write a custom Django management command. You can run the command using Django's standard manage.py.

Something like this:

from django.core.management.base import BaseCommand, CommandError
from example.models import YourModel

class Command(BaseCommand):
    args = ''
    help = ''

    def handle(self, *args, **options):

        # Get all objects
        objects = YourModel.objects.all()

        for object in objects: # For each object

            # If old file path:
            if not 'userID/projectID' in objects.filefield.name:
                # Move the file, eg usign shutil http://docs.python.org/library/shutil.html#shutil.move
                # Update filefield
                # save object
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
  • yeah, that's what I was referring to as a 'dumb loop through database' - I wonder if there was a reasonable way to do it - I'd probably have it included in .save() method of the model, in order to have it done online for frequenty accessed models first – qdot Feb 13 '12 at 19:33
  • 1
    'dumb loop' seems a clean solution that solves the issue once and for all. Overwriting save will just reduce the 'mess'. – Mariusz Jamro Feb 13 '12 at 21:45
  • just curious. if this is only intended to be run once, wouldn't it be better to implement as a data migration, but if you forsee yourself changing the file path/naming scheme in the future, do so as a mgmt cmd as above? – ckot Feb 19 '18 at 17:56
  • @ckot Migrations were added in 2014, the answer is from 2013 :) – Mariusz Jamro Feb 23 '18 at 16:18