Django多个数据库(健全性检查)

2024-05-15 13:53:24 发布

您现在位置:Python中文网/ 问答频道 /正文

下午好。我读过很多关于这个话题的地方,从每个地方都能得到一些信息,因为它们看起来并不一致,我相信我能做到这一点。由于这是一个测试设置,我不想花几个月的时间来发现某些东西不起作用——而事实证明这就是原因所在。在

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

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文件夹中)

^{pr2}$

(allow_migrate()中的elif不确定是否正确。也是allow_relationship()中的elif。我从一个例子中改编了这些)

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

提前致谢。在


Tags: djangonamepylocalhosthostdbportpostgresql
1条回答
网友
1楼 · 发布于 2024-05-15 13:53:24

这是我推荐的路由器。以下注释中的说明


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
        
        # I recommend returning 'default' here since 
        # it is your default database
        return 'default'

    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
        
        # 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'

    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.
        # I prefer to make this global by using the following syntax
        return obj1._meta.app_label == obj2._meta.app_label


    def allow_migrate(self, db, app_label, model_name=None, **hints):
        
        # 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

相关问题 更多 >