etianen / django-s3-storage

Django Amazon S3 file storage.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Setting similar to `AWS_S3_KEY_PREFIX` but instead prepend a dynamic param for each model's files

pljspahn opened this issue · comments

I have some other web services that will access files stored through Django/S3 and I'd like to keep my naming scheme consistent.

I have a Django model MyModel that will store up to 10 images for each instance. MyModel has a CharField that is set with unique=True and I'd like to use this field's value when uploading files to S3, as this field is used commonly with our business and is analogous to a SKU.

So for example, I have two model instances saved, "Item A" and "Item B". I want the files to be uploaded to S3 so that the path looks like /media/MyModel/<sku>/

Item A's image paths would look like:

/media/MyModel/ITM-A/item-a-base-photo.jpg
/media/MyModel/ITM-A/another-photo-of-item-a.jpg
/media/MyModel/ITM-A/these-photos-dont-have-consistent-naming-conventions.jpg
/media/MyModel/ITM-A/photo-9.jpg

Item B, like so:

/media/MyModel/ITM-B/some-photo.jpg
/media/MyModel/ITM-B/another-photo.jpg

Is there a strategy for having django-s3-storage build these dynamic paths for me when uploading files for each model's instance?

I'd prefer not to need to rely on tags assigned to each photo for this, as I plan to use tags in a different manner and being able to just access the images by path would be preferable.

This has nothing to do with django-s3-storage really. You can pass a callable to upload_to as follows:

models.FileField(..., upload_to=file_upload_to) with an implementation similar to this:

def file_upload_to(instance, filename):
    return f"{instance._meta.label_lower}/{instance.sku}/{filename}"

(Maybe not exactly like this but you should be able to adapt the code in your project.)

I was tunnel visioned into trying to dynamically set the AWS_S3_KEY_PREFIX that I entirely forgot about just using upload_to.

Thanks.