1

I have a SQL dump of a legacy DB, and a folder with images, and those are referenced by some rows of certain tables, and I need to migrate that data to the new Django models. The specific problem is how to "perform" the upload, but in a management command.

When the table with the field referenced is migrated to it's corresponding model, I need to also set the image field of the model, and I also need to process the filename accordingly to the upload_to parameter for the ImageField.

How to programmatically populate the image field from a file path or a file descriptor?

Armando Pérez Marqués
  • 5,661
  • 4
  • 28
  • 45

1 Answers1

0

One approach would be to create a utility django project specifying your legacy database in settings.py. Then use the inspectdb management command to create a django model representation of your legacy database. And finally use dumpdata to get you data in JSON format.

You could then finally make your own JSON script that inserts your old data in your new models.

benjaoming
  • 2,135
  • 1
  • 21
  • 29
  • I have thought about this, but still the problem remains, because the path is incorrect. Also, I want the import operation to regenerate the new filename accordingly to the `upload_to` parameter. – Armando Pérez Marqués Nov 27 '11 at 05:15
  • An ImageField is actually just a CharField. So you can simply manipulate its value as if it was a string. Ie. do image_field = image_field.replace("old_path/", "new_path/") – benjaoming Nov 28 '11 at 16:48
  • That's what I'm doing right now. The old field value contains only the base name of the image file, so I pass that value to the `upload_to` attribute of the ImageField instance attached to the model, in conjunction with the instance being created. Then, I copy the original file contents (the directory containing all the images is an argument of the script) to the returned value of `upload_to` call, joined to the `MEDIA_ROOT` setting. It works, but, is this portable to other kind of file storage, like cloud services? – Armando Pérez Marqués Nov 29 '11 at 04:10
  • From what I can make of the documentation, a FileField is ALWAYS a CharField and it even validates that the content is a valid unix path. Any kind of storage system will only get such data as the key to retrieve the actual data stored, whether it's in the cloud or on your disk. – benjaoming Nov 30 '11 at 19:48