代码之家  ›  专栏  ›  技术社区  ›  HurnsMobile

django 1.2中的多数据库配置

  •  20
  • HurnsMobile  · 技术社区  · 15 年前

    希望这是一个简单的问题。

    我在理解Django1.2中新的多数据库特性的文档时遇到了一些问题。首先,我似乎找不到一个例子来说明您如何在其中一个模型中实际使用第二个数据库。

    在models.py中定义新类时,如何指定要连接到哪个数据库?

    my settings.py包含类似于-

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', 
            'NAME': 'modules',
            'USER': 'xxx',                      
            'PASSWORD': 'xxx',                  
        },
        'asterisk': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'users',                     
            'USER': 'xxxx',                      
            'PASSWORD': 'xxxx',                  
        }
    
    }
    

    编辑:我像个傻瓜一样阅读路由器上的文档。如果其他人正在为此挣扎,请确保在放弃之前阅读2到3次!

    3 回复  |  直到 15 年前
        1
  •  25
  •   Jordan Reiter    15 年前

    是的,有点复杂。

    有很多方法可以实现它。基本上,您需要某种方式来指示哪些模型与哪个数据库相关联。

    第一选择

    这是我使用的代码;希望能有所帮助。

    from django.db import connections
    
    class DBRouter(object):
        """A router to control all database operations on models in
        the contrib.auth application"""
    
        def db_for_read(self, model, **hints):
            m = model.__module__.split('.')
            try:
                d = m[-1]
                if d in connections:
                    return d
            except IndexError:
                pass
            return None
    
        def db_for_write(self, model, **hints):
            m = model.__module__.split('.')
            try:
                d = m[-1]
                if d in connections:
                    return d
            except IndexError:
                pass
            return None
    
        def allow_syncdb(self, db, model):
            "Make sure syncdb doesn't run on anything but default"
            if model._meta.app_label == 'myapp':
                return False
            elif db == 'default':
                return True
            return None
    

    它的工作方式是创建一个包含模型的数据库名文件。在您的案例中,您将创建一个单独的 models -已调用样式文件 asterisk.py 与应用程序的模型位于同一文件夹中。

    在你 models.py 文件,你会添加

    from asterisk import *
    

    然后,当您实际从该模型请求记录时,它的工作方式如下:

    1. records = MyModel.object.all()
    2. 模块用于 MyModel myapp.asterisk
    3. 有一个叫做“星号”的连接,所以使用 而不是“违约”

    第二选择

    如果您希望对数据库选择的每个模型进行控制,那么这样的方法可以工作:

    from django.db import connections
    
    class DBRouter(object):
        """A router to control all database operations on models in
        the contrib.auth application"""
    
        def db_for_read(self, model, **hints):
            if hasattr(model,'connection_name'):
                return model.connection_name
            return None
    
        def db_for_write(self, model, **hints):
            if hasattr(model,'connection_name'):
                return model.connection_name
            return None
    
        def allow_syncdb(self, db, model):
            if hasattr(model,'connection_name'):
                return model.connection_name
            return None
    

    然后,对于每个模型:

    class MyModel(models.Model):
        connection_name="asterisk"
        #etc...
    

    请注意,我没有测试第二个选项。

        2
  •  8
  •   Rich    15 年前

    约旦回答的附录。对于第二个选项,allow\u syncdb方法正确工作如下:

    def allow_syncdb(self, db, model):
        if hasattr(model,'connection_name'):
            return model.connection_name == db
        return db == 'default'
    
        3
  •  3
  •   Daniel Roseman    15 年前
    推荐文章