Django 模型文件字段存储使用类取决于设置



我想在本地和 aws s3 中管理 django 多媒体文件,我拥有所有配置,如果我在模型中指定存储类,它可以正常工作,但这并不实用,因为我每次都必须进行迁移,但我想确定文件配置依赖于名为"FILES"的配置变量以编程方式工作。

这是代码

settings.py

FILE_OVERWRITE = True
if FILES == 'LOCAL':
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIAFILES_STORAGE = 'app.files.CustomStorage'
MEDIA_URL = '/media/'
elif FILES == 'AWS':
MEDIAFILES_STORAGE = 'app.files.MediaStorage'
MEDIA_URL='https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, MEDIA_LOCATION)

storages.py

class CustomStorage(FileSystemStorage):
def get_available_name(self, name, *args, **kwargs):
if self.exists(name):
if settings.FILE_OVERWRITE:
os.remove(os.path.join(settings.MEDIA_ROOT, name))
else:
alternative_name = name.split('.')
name = alternative_name[0] + str(timezone.now()).split(' ')[0] + '.' + alternative_name[1]
return name
class MediaStorage(S3Boto3Storage):
location = settings.MEDIA_LOCATION
file_overwrite = settings.FILE_OVERWRITE

models.py

class Bill(ChangesMixin, models.Model):
#pdf = models.FileField(storage=CustomStorage(), upload_to='media/', blank=True, null=True) <-- on local with this class works well
#pdf = models.FileField(storage=MediaStorage(), upload_to='media/', blank=True, null=True)  <-- on aws with this class works well
# throw an error because settings class name is not callable
pdf = models.FileField(storage=settings.MEDIAFILES_STORAGE, upload_to='media/', blank=True, null=True)

有人可以帮助我吗?我该怎么做?

提前谢谢。

DEFAULT_FILE_STORAGE设置允许您设置默认使用的存储。这样就无需将"存储"分配给各个字段,并且即使存储发生更改也无需创建迁移文件。

文档:https://docs.djangoproject.com/en/3.0/ref/settings/#default-file-storage

我建议将 settings.py 分离到 local.py 和 production.py 配置文件。这消除了配置文件中的 if 语句。看看我正在处理的项目的配置文件:https://github.com/youngminz/mma-portal/tree/master/mma_portal/settings

最新更新