django-storages 获取完整的 S3 url

Joh*_*eer 9 python django amazon-s3

我有几个类在 Amazon S3 中使用 django-storages

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

现在我需要获取缓存文件位置的 url。

cache = cache.objects.get(identifier=identifier)
cache_file = cache.cache_file
Run Code Online (Sandbox Code Playgroud)

缓存文件是一个FieldFile包含storage对象的对象。

在数据库中,我只能看到cache/file.json我之前保存的值。

在这种情况下,我不需要获取文件,而是获取文件所在的完整 url。
我怎么能得到这个?

Dra*_*obZ 9

我知道这个问题已经得到了回答,但以防万一有人在我偶然发现这个问题时正在寻找我需要的东西......

我发现对于大型查询,report.file.url在我需要提取大量记录的情况下,从模型实例 ( )中提取 url 会导致糟糕的性能,因为 Django 在以这种方式访问​​模型字段时对每条记录执行数据库查询。这是替代方法的示例实现,您可以在其中预先执行整个查询,并在需要时仍然获取 url。

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
]
Run Code Online (Sandbox Code Playgroud)

  • 我认为值得补充的是,如果我们有一个带有 `FileField` 的 `obj`,即 `obj.file` => 我们需要调用 `media_storage.url(obj.file.name)` 来获取正确的 boto S3网址。 (2认同)

小智 5

该文件应位于:

cache = cache.objects.get(identifier=identifier)
cache_file = cache.cache_file
cache_file_url = cache.cache_file.url
Run Code Online (Sandbox Code Playgroud)

调用它以获取完整的 S3 URL,但您应该设置 django 存储来获取它。