django.db.utils.ConnectionDoesNotExist:连接prueba不存在

Posted

技术标签:

【中文标题】django.db.utils.ConnectionDoesNotExist:连接prueba不存在【英文标题】:django.db.utils.ConnectionDoesNotExist: The connection prueba doesn't exist 【发布时间】:2022-01-23 03:17:42 【问题描述】:

我想用 Djongo 将 Django 数据库迁移到 MongoDB,但是我遇到了这个错误。 我正在尝试连接到 MongoDB Atlas 数据库。

Traceback (most recent call last):
  File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/db/utils.py", line 167, in ensure_defaults
    conn = self.databases[alias]
KeyError: 'prueba'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 74, in handle
    connection = connections[db]
  File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/db/utils.py", line 199, in __getitem__
    self.ensure_defaults(alias)
  File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/db/utils.py", line 169, in ensure_defaults
    raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)
django.db.utils.ConnectionDoesNotExist: The connection prueba doesn't exist

我的settings.py如下:

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'decide',
        'PASSWORD': 'decide',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    ,
    'prueba': 
        'ENGINE': 'djongo',
        'NAME': 'egc-sierrezuela-2',
        'ENFORCE_SCHEMA': False,
        'CLIENT': 
            'HOST': 'mongodb+srv://usuario:password@egc-sierrezuela-2.fxrpl.mongodb.net/egc-sierrezuela-2?retryWrites=true&w=majority'
        
    

我正在使用Django==2.0djongo==1.2.38

我尝试了许多 djongo 版本,但仍然出现错误。 此外,由于我使用的是旧项目,因此无法将 django 升级到最新版本。

有什么想法吗?

【问题讨论】:

请查看self.databases有哪些信息。有prueba 吗? 您好,我不知道如何查看self.databases 信息,如何访问? 在使用前打印。 print(self.databases) 我在settings.py 中声明后打印了它,我收到以下错误NameError: name 'self' is not defined 【参考方案1】:

当没有正确准备 db_routers 文件时,我遇到了类似的错误 (docs)。 假设你的应用结构是这样的:

your-app/
├── app
├── db_routers.py
├── settings.py

在您的设置文件中,您应该提供路由器的路径:

DATABASE_ROUTERS = ('db_routers.DatabaseRouter',)

假设你的模型是 ModelPostgres 和 ModelMongo,定义你的 db_routers 文件如下:

from app.models import ModelPostgres, ModelMongo


class DatabaseRouter:

    def db_for_read(self, model, **hints):
        '''You dont need to define Postgres model here since its in default database'''
        if model is ModelMongo:
            return "prueba"
        return None

    def db_for_write(self, model, **hints):
        if model is ModelMongo:
            return "prueba"
        return None

    def allow_relation(self, obj1, obj2, **hints):
        '''Optional, but multidatabase relations are not really supported by django'''
        if obj1._meta.model == ModelMongo and obj2._meta.model == ModelPostgres:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        '''Here you can get app label name or model name or hints from migrations files'''
        if model_name == ModelMongo.__name__.lower():
            return db == "prueba"
        else:
            return db == "default"

所以它应该有助于迁移,因此您将在 mongo 数据库中拥有 mongo 模型,在 postgres 数据库中拥有其他模型。并且在从数据库中写入和读取时,djongo 会知道它应该使用哪个数据库。 如果您将应用程序分离为 mongo 和 postgres,那么您还可以在“allow_migrate”函数中使用应用程序标签:

def allow_migrate(self, db, app_label, model_name=None, **hints):
    '''If you have one app for mongo and one for postgres, then you can use app_label'''
    if app_label == "mongo_app":
        return db == "prueba"
    else:
        return db == "default" 

【讨论】:

以上是关于django.db.utils.ConnectionDoesNotExist:连接prueba不存在的主要内容,如果未能解决你的问题,请参考以下文章