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?
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
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With