Django:在 运行 迁移期间更改设置值

Django: Change settings value during run-time in migrations

我正在尝试在 运行 期间更改 settings.py 中的值,同时创建迁移。

settings.py:

...
magicVar = "initValue"

0002_init:

...
def change_magicVar(apps, schema_editor):
    settings.magicVar = "newValue"
...

operations = [
    migrations.RunPython(change_magicVar),
]
...

0003_changed_migrations:

...
def print_magicVar(apps, schema_editor):
   # Yay! It prints the correct value
   print (settings.magicVar) # prints: newValue
...

operations = [
   migrations.RunPython(print_magicVar),
   migrations.CreateModel(
     name='MagicModel',
        fields=[
            ('someMagic', 
               models.ForeignKey(
                  # Oops! This still has the old value, i.e *initValue*
                  # I want to achieve the *newValue* here!
                  default=settings.magicVar,
                  ... 
    )),

我想在迁移中更改值,但看起来该值已被缓存。 django 是否提供抽象来刷新迁移缓存并在其中放入新值?如果不是,我有什么可能的选择来在默认值中实现该值?

注意: 我试图避免 this solution 因为我的数据库可能会提供数百万条记录并且迭代它们并不理想。

出于外部原因,我也在努力避免django-livesettings

谢谢!

你不能这样实现。您可以查看 https://github.com/jazzband/django-constance .