如何将两个Django项目与不同的数据库集成?

时间:2017-03-29 13:18:41

标签: python django postgresql

我的原始Django项目在sqlite3数据库上运行。我想整合另一个来自GitHub的Django项目,该项目运行在postgre数据库上。我在requirements.txt文件中添加了github链接&安装它并在settings.py文件的原始INSTALLED_APPS部分添加了新的Django项目应用程序,并更新了原始项目的urls.py文件。现在我被how to combine settings.py of these two projects?

困住了

当我运行命令

python manage.py migrate

然后它给了我这个错误: - AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'

正确的设置已经在github下载的django项目中,但不在原始项目中。

我已经阅读了Stack Overflow以及官方文档上的几乎所有答案。但能够理解。 如果这是一个重复或愚蠢的问题我会道歉。

1 个答案:

答案 0 :(得分:1)

根据文档,您需要通过以下方式编辑您的设置: 1)添加一个名为ex databases.py

的新文件
DATABASES = {
'default': {},
'auth_db': {
    'NAME': 'auth_db',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'swordfish',
},
'primary': {
    'NAME': 'primary',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'spam',
},
'replica1': {
    'NAME': 'replica1',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'eggs',
},
'replica2': {
    'NAME': 'replica2',
    'ENGINE': 'django.db.backends.mysql',
    'USER': 'mysql_user',
    'PASSWORD': 'bacon',
},

2)对于authrouter文件,请参阅文档,这里有一个示例:

import random

class PrimaryReplicaRouter(object):
    def db_for_read(self, model, **hints):
        """
        Reads go to a randomly-chosen replica.
        """
        return random.choice(['replica1', 'replica2'])

    def db_for_write(self, model, **hints):
        """
        Writes always go to primary.
        """
        return 'primary'

    def allow_relation(self, obj1, obj2, **hints):
        """
        Relations between objects are allowed if both objects are
        in the primary/replica pool.
        """
        db_list = ('primary', 'replica1', 'replica2')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        All non-auth models end up in this pool.
        """
        return Trueta.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

3)在您的settings.py中删除数据库架构并添加此行

DATABASE_ROUTERS = ['yourapp.filename.CLASS']

当你要午餐时,命令"迁移"添加--database = databasename以应用它们 有关详细信息,请参阅https://docs.djangoproject.com/en/1.10/topics/db/multi-db/