Django多个数据库 - 关系不存在;第1行:SELECT COUNT(*)AS“__count”FROM

时间:2017-01-14 17:36:09

标签: python django django-models django-admin

我使用的是两个数据库,其中一个是Mysql,另一个是PostgreSql。

  • Mysql定义为'default',PostgreSql定义为'location_db'

  • 我有5个应用,请说'a,b,c,d,位置'应用,

  • 除了位置应用

  • 之外,所有应用都应在“默认”数据库上运行
  • 我只是做'python manage.py runserver'然后一切正常,甚至网站工作正常,但当我在管理页面然后点击'位置'管理模型时,它运行错误 *关系“location_locationmodel”不存在;第1行:SELECT COUNT(*)AS“__count”FROM“location_locationmodel”* 在另一方面,如果我点击'abcd'管理模型,它就可以正常工作。

1)这是router.py(我只是从doc.django网站获取路由器代码可能代码不适合我,因为我只是猜测我的路由器配置不正确?可能吗?)

class LocationRouter(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 location_db.
        """
        if model._meta.app_label == 'location':
            return 'location_db'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to location_db.
        """
        if model._meta.app_label == 'location':
            return 'location_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the events app is involved.
        """
        if obj1._meta.app_label == 'location' or \
           obj2._meta.app_label == 'location':
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'location_db'
        database.
        """
        if app_label == 'location':
            return db == 'location_db'
        return None

2)这是settings.py

DATABASE_ROUTERS = ['location.router.LocationRouter']

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'OPTIONS': {
            'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
        },
    },
    'location_db': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'geo',
        'USER': 'john',
        'PASSWORD': 'toor',
        'HOST': 'localhost',
        'PORT': '5432',
    },
}

*我的预测*

1)如果我创建另一个项目并且只使用PostgreSql,那么每件事都可以正常工作,所以所有数据库都可以正常工作

2)这是我做'python manage.py makemigrations或者'的时候:

Operations to perform:
  Apply all migrations: admin, auth, a, contenttypes, location, b, c, d, registration, sessions, sites
Running migrations:
  No migrations to apply.

*迁移的结果我认为不应该附带'location'应用程序或者来自 。这只是我不知道的预测,但当我在管理页面点击“位置”管理模型时,它会运行错误,但是当我只使用一个数据库时,它不会运行错误, 我的意思是它还在mysql数据库中搜索表吗?可能是路由器配置不正确? *

2 个答案:

答案 0 :(得分:4)

下面的代码帮助我解决了这个问题

python manage.py migrate --run-syncdb

答案 1 :(得分:1)

Okey Guys解决方案并不是太远了如果你没有因为失眠而痛苦,在这种情况下你只是指明一切

  • python manage.py迁移位置--database = location_db

就在这里,你的查询在postgresql数据库中匹配:)祝你好运

相关问题