如何让Django在使用命令行参数启动时选择特定的默认数据库

时间:2021-07-29 21:16:16

I want Django to use a specific database(sqlite) as default by an argument given when It starts up regardless of settings.py. For this purpose, I added below code in manage.py so that settings.DATABASES can be set with the argument when it starts up.

我希望Django使用特定的数据库(sqlite)作为默认值,无论settings.py如何启动它都会给出一个参数。为此,我在manage.py中添加了以下代码,以便在启动时可以使用参数设置settings.DATABASES。

# manage.py

from myapp import settings
settings.DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(settings.DB_PATH, sys.argv[3]),
    },
}

But It doesn't work....Django still accesses origin database represented in settings.py

但它不起作用.... Django仍然访问settings.py中表示的原始数据库

I think it is because Django already has done with setting default DB before I change settings.DATABASES in manage.py.

我认为这是因为在我更改manage.py中的settings.DATABASES之前,Django已经完成了设置默认数据库的工作。

As a result, the change doesn't have any effect.

结果,这种变化没有任何影响。

When does Django choose default database with settings? If I can change settings.DATABASES before Django choose default database, I will work i think.

Django什么时候选择设置默认数据库?如果我可以在Django选择默认数据库之前更改settings.DATABASES,我会认为。

Is there any way to change default database at runtime? So that even Django choose already default database I can change it.

有没有办法在运行时更改默认数据库?所以即使Django选择已经默认的数据库我也可以改变它。

It doesn't mean to change database dynamically using `model.objects.using('dbname').

它并不意味着使用`model.objects.using('dbname')动态更改数据库。

1 个解决方案

#1


1  

./manage.py migrate --database=default

#1


1  

./manage.py migrate --database=default