Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-storages get the full S3 url

I have a couple of classes using django-storages with Amazon S3

class Cache(models.Model):
    identifier = models.TextField(blank=True, null=True)
    cache_file = models.FileField(upload_to="cache")

Now I need to get the url for the cache file location.

cache = cache.objects.get(identifier=identifier)
cache_file = cache.cache_file

cache file is a FieldFile object which contains a storage object.

in the database I only see the value cache/file.json which I saved earlier.

In this case I do not need to get the file, but the full url where the file is located.
How would I be able to get this?

like image 577
Johan Vergeer Avatar asked Jun 23 '16 13:06

Johan Vergeer


1 Answers

I know this question is already answered, but just in case someone is looking for what I needed when I stumbled across this question...

I found for large queries that pulling the url off of the model instance (report.file.url) was resulting in terrible performance in cases where I need to pull a lot of records, because Django does a database query per record when accessing model fields this way. Here is an example implementation of an alternate method where you can do the entire query up front and still get the url if you need it.

from django.core.files.storage import get_storage_class
from . import models

# instance of the current storage class
media_storage = get_storage_class()()

# grabs all of my reports at once and stores them in a list of dicts
# instead of separate Report instances
report_list = models.Report.objects.values()

# stick the urls into the my records
report_list = [
        {**report, "url": media_storage.url(report["file"])} 
        for report in report_list
]
like image 146
DragonBobZ Avatar answered Oct 02 '22 13:10

DragonBobZ