具有多个数据库后端和数据库路由的GeoDjango

时间:2019-10-16 17:12:02

标签: python postgis geodjango

我有两个数据库设置,一个是Postgres数据库,一个是PostGIS数据库。然后将连接设置定义为:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': ENV('POSTGRES_DB'),
        'USER': ENV('POSTGRES_USER'),
        'PASSWORD': ENV('POSTGRES_PASSWORD'),
        'HOST': ENV('POSTGRES_HOST', default='localhost'),
        'PORT': ENV('POSTGRES_PORT', default='5432'),
    }
}

DATABASES['gis'] = {
    'ENGINE': 'django.contrib.gis.db.backends.postgis',
    'NAME': ENV('POSTGIS_DB'),
    'USER': ENV('POSTGIS_USER'),
    'PASSWORD': ENV('POSTGIS_PASSWORD'),
    'HOST': ENV('POSTGIS_HOST', default='postgis'),
    'PORT': ENV('POSTGIS_PORT', default='5432'),
}

我还有两个应用程序,其中一个我要使用PostGIS数据库(称为study_gis,另一个要使用默认数据库。因此,我设置了一个数据库路由器(dbRouter.py):

class StudyGISDBRouter(object):
    """
    A router to control gis db operations
    """
    def db_for_read(self, model, **hints):
        "Point all operations on study_gis models to 'gis'"
        from django.conf import settings
        if 'gis' not in settings.DATABASES:
            return None
        if model._meta.app_label == 'study_gis':
            return 'gis'
        return None

    def db_for_write(self, model, **hints):
        "Point all operations on study_gis models to 'gis'"
        from django.conf import settings
        if 'gis' not in settings.DATABASES:
            return None
        if model._meta.app_label == 'study_gis':
            return 'gis'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        "Allow any relation if a model in study_gis is involved"
        from django.conf import settings
        if 'gis' not in settings.DATABASES:
            return None
        if obj1._meta.app_label == 'study_gis' or obj2._meta.app_label == 'study_gis':
            return True
        return None

    def allow_syncdb(self, db, model):
        "Make sure the study_gis app only appears on the 'gis' db"
        from django.conf import settings
        if 'gis' not in settings.DATABASES:
            return None
        if db == 'gis':
            return model._meta.app_label == 'study_gis'
        elif model._meta.app_label == 'study_gis':
            return False
        return None

然后我将路由器安装到我的设置文件中:

DATABASE_ROUTERS = [
    'study_gis.dbRouter.StudyGISDBRouter'
]

问题:

尝试迁移时,出现以下错误:

AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'

对于其他具有类似错误的帖子,通常的答案是确保引擎使用的是postgis后端。但是由于我在gis数据库设置中确实有此问题,所以我不知道是什么原因引起的。

如何确保一个应用程序正在使用正确的数据库,而不是路由器中已有的数据库?

0 个答案:

没有答案