迁移引用动态存储不一致

时间:2019-06-11 13:13:30

标签: python django django-storage

我希望模型中的特定字段使用S3存储(如果设置具有AWS_ACCESS_KEY_ID)或回退到default_storage。我正在使用django-storages

要实现此目的,请在models.py中:

from django.db import models
from django.conf import settings
from .storage_backends import variativeStorage

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    photo = models.ImageField(upload_to='/public', default='dummy-img.png', storage=variativeStorage())

storage_backends.py:

from storages.backends.s3boto3 import S3Boto3Storage
from django.core.files.storage import default_storage
from django.conf import settings


def variativeStorage():
    """Return S3Boto3Storage if access key is defined.
    Fallback to default storage.
    """
    if hasattr(settings, 'AWS_ACCESS_KEY_ID') and settings.AWS_ACCESS_KEY_ID:
        return S3Boto3Storage()
    return default_storage

它工作得很好,但是问题出在迁移上-它评估字段storage当前具有的Django设置。因此,如果我们没有AWS_ACCESS_KEY_IDmakemigrations可以做到:

operations = [
        migrations.AlterField(
            model_name='profile',
            name='photo',
            field=models.ImageField(default='dummy-img.png', upload_to='/public'),
        ),
    ]

并且如果有的话:

operations = [
        migrations.AlterField(
            model_name='profile',
            name='photo',
            field=models.ImageField(default='dummy-img.png', storage=storages.backends.s3boto3.S3Boto3Storage(), upload_to='/public'),
        ),
    ]

因此在生产环境中运行服务器将触发缺少迁移的警告:

remote: Running migrations:
remote: No migrations to apply.
remote: Your models have changes that are not yet reflected in a migration, and so won't be applied.
remote: Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

是否有一致的方式对字段进行动态存储?如何进行variativeStorage的惰性求值,或者也许删除该特定字段的迁移生成?

0 个答案:

没有答案