I was working with a table that had a similar (simplified) structure like this:
| uuid | file_path |
|----------------------------------|---------------------------|
| b8658dfc3e80446c92f7303edf31dcbd | media/private/file_1.pdf |
| 3d750874a9df47388569a23c559a4561 | media/private/file_2.csv |
| d177b7f7d8b046768ab65857451a0354 | media/private/file_3.txt |
| df45742175d7451dad59761f15653d9d | media/private/image_1.png |
| a542966fc193470dab84351c15523042 | media/private/image_2.jpg |
Let’s say the above table is represented by the following Django model:
from django.db import models
class FileCabinet(models.Model):
uuid = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False
)
file_path = models.FileField(upload_to="files/")
I needed to extract the file names with their extensions from the file_path column and
create new paths by adding the prefix dir/ before each file name. This would involve
stripping everything before the file name from a file path and adding the prefix, resulting
in a list of new file paths like this: ['dir/file_1.pdf', ..., 'dir/image_2.jpg'].