首页 > 解决方案 > Django:在迁移运行时更改设置值

问题描述

我试图settings.py在创建迁移时在运行时更改值。

设置.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 是否提供了一种抽象来刷新迁移缓存并在其中添加新值?如果不是,我有哪些可能的选择才能在默认值中实现该值?

注意:我试图避免这种解决方案,因为我的数据库可能会提供数百万条记录,并且对它们进行迭代并不理想。

由于外部原因,我也试图避免使用django-livesettings

谢谢!

标签: pythondjangodjango-migrations

解决方案


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


推荐阅读