python - Django 多数据库(完整性检查)

标签 python django database router

下午。我已经阅读了很多关于该主题的地方,从每个地方获取信息,因为它们看起来并不一致,并且相信我有这个工作。由于这是一个测试设置,我不想花几个月的时间才发现有什么东西不工作了 --- 事实证明是因为这个。

感谢那些比我更有经验的人看过这个,并请提出任何建议。

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'myproject',
    'USER': 'myprojectuser',
    'PASSWORD': 'abc123',
    'HOST': 'localhost',
    'PORT': '',
},
'ta1_db': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'testapp1db',
    'USER': 'ta1',
    'PASSWORD': 'ta1',
    'HOST': 'localhost',
    'PORT': '',
},
'ta2_db': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'testapp2db',
    'USER': 'ta2',
    'PASSWORD': 'ta2',
    'HOST': 'localhost',
    'PORT': '',
},
}

DATABASE_ROUTERS = ['spiderproject.routers.DBRouter',]

routers.py(在主 spiderproject 文件夹中)

class DBRouter(object):

def db_for_read(self, model, **hints):
    """Send all read operations on 'app_label' app models to associated db"""
    if model._meta.app_label == 'testapp1':
        return 'ta1_db'
    if model._meta.app_label == 'testapp2':
        return 'ta2_db'
    return None

def db_for_write(self, model, **hints):
    """Send all write operations on 'app_label' app models to associated db"""
    if model._meta.app_label == 'testapp1':
        return 'ta1_db'
    if model._meta.app_label == 'testapp2':
        return 'ta2_db'
    return None

def allow_relation(self, obj1, obj2, **hints):
    """Determine if relationship is allowed between two objects."""

    # Allow any relation between two models that are in the same app.
    if obj1._meta.app_label == 'testapp1' and obj2._meta.app_label == 'testapp1':
        return True
    if obj1._meta.app_label == 'testapp2' and obj2._meta.app_label == 'testapp2':
        return True
    # No opinion if neither object is in the Example app (defer to default or other routers).
    elif 'testapp1' not in [obj1._meta.app_label, obj2._meta.app_label] and 'testapp2' not in [obj1._meta.app_label, obj2._meta.app_label]:
        return None

    # Block relationship if one object is in the Example app and the other isn't.
        return False

def allow_migrate(self, db, app_label, model_name=None, **hints):
    """Ensure that the 'app_label' app's models get created on the right database."""
    if app_label == 'testapp1':
        return db == 'ta1_db'
    if app_label == 'testapp2':
        return db == 'ta2_db'
    elif db == 'default':
        # Ensure that all other apps don't get migrated on the example_db database.???
        return False

    # No opinion for all other scenarios
    return None

(我不确定 allow_migrate() 中的 elif 是否正确。还有 allow_relation() 中的 elif。我从示例中改编了这些)

我已经在它们自己的 admin.py 中注册了 testapp1 和 testapp2 的模型,它们出现在管理页面上——此时添加/删除数据是可以的,我检查它们是独立存储的。

非常感谢。

最佳答案

这是我推荐的路由器。在下面的评论中解释


class DBRouter(object):
    def db_for_read(self, model, **hints):
        """Send all read operations on 'app_label' app models to associated db"""
        if model._meta.app_label == 'testapp1':
            return 'ta1_db'
        if model._meta.app_label == 'testapp2':
            return 'ta2_db'
        # return None
        <b>
        # I recommend returning 'default' here since 
        # it is your default database
        return 'default'</b>

    def db_for_write(self, model, **hints):
        """Send all write operations on 'app_label' app models to associated db"""
        if model._meta.app_label == 'testapp1':
            return 'ta1_db'
        if model._meta.app_label == 'testapp2':
            return 'ta2_db'
        # return None
        <b>
        # I recommend returning 'default' here since 
        # it is your default database, this will allow
        # commonly used django apps to create their
        # models in the default database (like contenttypes 
        # and django auth
        return 'default'</b>

    def allow_relation(self, obj1, obj2, **hints):
        """Determine if relationship is allowed between two objects."""

        # Allow any relation between two models that are in the same app.
        <b># I prefer to make this global by using the following syntax</b>
        return obj1._meta.app_label == obj2._meta.app_label


    def allow_migrate(self, db, app_label, model_name=None, **hints):
        <b>
        # I think this was your biggest misunderstanding
        # the db_for_write will pick the correct DB for the migration
        # allow_migrate will only let you say which apps/dbs you 
        # should not migrate.  I *strongly* recommend not taking
        # the belt and braces approach that you had here.        
        return True</b>

关于python - Django 多数据库(完整性检查),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44861050/

相关文章:

python - 在 django 映射中如何获取选择字段的完整计数

Django Factory Boy 创建 vs create_batch

django - CSRF 验证失败 - 引用者不安全,而主机安全

mysql - 尝试为我的广告创建表格时出现代码错误

php - Doctrine2 查询生成器 - 关联数据未正确补水

python - 使用 matplotlib 显示灰度 OpenCV 图像

python - Plpython 程序中的 Greenplum pandas 数据框集成(来自数据库内部)

c# - SQLCommand ExecuteNonQuery 最大 CommandText 长度?

python - Robot Framework 的 Mongo Db 扩展库返回错误记录

python - 是否有 Python 模块允许我创建命令行界面,如 CMD?