【问题标题】:Not able to use Query set for multiple databases in django无法在 django 中为多个数据库使用查询集
【发布时间】:2012-02-12 15:27:42
【问题描述】:

我可以为默认数据库使用查询集。 但是当我对另一个数据库使用查询集时,抛出异常。

在我的应用程序中,我使用了两个数据库。 sqlite 和 Mysql

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'abc.db',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    },
      'second' : {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'abc',                      # Or path to database file if using sqlite3.
        'USER': 'abcdb',                      # Not used with sqlite3.
        'PASSWORD': 'xxxxx',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
          }
}

当我为第一个数据库使用查询集时,它不会引发任何异常。 使用第二个数据库时,它抛出的表不可用。

TemplateSyntaxError at /abc/xyz/

Caught DatabaseError while rendering: no such table: second.tablename

Request Method:     GET
Request URL:    http://127.0.0.1:8000/xxx/yyyy/?q=abcd
Django Version:     1.3.1
Exception Type:     TemplateSyntaxError
Exception Value:    

Caught DatabaseError while rendering: no such table: second.tablename

【问题讨论】:

  • 您确定该表存在于数据库中吗?
  • 您是否创建了路由器(docs.djangoproject.com/en/dev/topics/db/multi-db/#using-routers)?很可能该表仅在其中一个数据库中(而不是 Django 在尝试查询时抛出)。
  • database1 有不同的表,database2 有不同的表。
  • database1 有不同的表,database2 有不同的表。当我运行以下命令时,shell = db2models.tablename.objects.get(name='abc') 抛出异常 DatabaseError: no such table: xyz

标签: python django django-queryset django-database


【解决方案1】:

感谢汤姆的回复, 我手动尝试了第二个数据库,它对我有用。

   $model_seconddb.modelname.objects.using('seconddatabasename').filter(name='xxx')

这可以在两个数据库中的所有表都不存在时使用。

当你想使用默认数据库时,没有使用(使用)的要求。 它会直接从默认数据库中查询。

【讨论】:

    【解决方案2】:

    在 Django 中使用多个数据库的最佳选择也是使用路由来管理多个数据库,这里是文档:

    https://docs.djangoproject.com/en/1.11/topics/db/multi-db/#topics-db-multi-db-routing

    这里是文档中的完整示例:

    class AuthRouter(object):
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.app_label == 'auth':
            return 'auth_db'
        return None
    
    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        if model._meta.app_label == 'auth':
            return 'auth_db'
        return None
    
    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the auth app is involved.
        """
        if obj1._meta.app_label == 'auth' or \
           obj2._meta.app_label == 'auth':
           return True
        return None
    
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        if app_label == 'auth':
            return db == 'auth_db'
        return None
    

    如果不指定查询中的数据库,Django 将在表名的基础上使用正确的数据库。

    希望有帮助:)

    【讨论】:

      猜你喜欢
      • 2020-01-22
      • 2019-08-17
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多