2

正如在此处链接的上一个问题中所述,我正在将上传到 S3 的图像保存在 Django 中。图像已经存在于 S3 中,我想通过创建媒体对象以编程方式将图像添加到 Django。

Django storages S3 - 存储现有文件

我的课看起来像这样:

class Media( models.Model ):
    asset_title = models.CharField( 'Title', max_length=255, help_text='The title of this asset.' )
    image_file = models.ImageField( upload_to='upload/%Y/%m/%d/', blank=True )

在我看来,我有这个:

bucket = s3.Bucket('my-bucket')

for my_bucket_object in bucket.objects.filter(Prefix='media/upload/2020'):
    djfile = Media.objects.create(asset_title=my_bucket_object.key, image_file=my_bucket_object)

我目前收到 AttributeError: 's3.ObjectSummary' 对象没有属性 '_committed'

4

1 回答 1

1

s3.ObjectSummary对象可能不会被 Django 识别为图像对象。

试试这个

from django.core.files.base import ContentFile

bucket = s3.Bucket('my-bucket')

for my_bucket_object in bucket.objects.filter(Prefix='media/upload/2020'):
    djfile = Media.objects.create(asset_title=my_bucket_object.key, image_file=ContentFile(my_bucket_object))  

ContentFile 类继承自 File,但与 File 不同,它对字符串内容(也支持字节)进行操作,而不是实际的文件
文档

于 2021-02-22T18:35:19.233 回答